repo_id
stringclasses
1 value
file_path
stringlengths
117
174
content
stringlengths
8
42.4k
__index_level_0__
int64
0
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/EventHistoryResultHandler.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; /** Interface defining a callback which contains the result of event history database operations. */ public interface EventHistoryResultHandler<T> { void call(final T value); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/Extension.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.adobe.marketing.mobile.internal.CoreConstants; import com.adobe.marketing.mobile.services.Log; import java.util.Map; /** Abstract class that defines an {@code Extension} */ public abstract class Extension { @NonNull private final ExtensionApi extensionApi; /** * Construct the extension and initialize with the {@code ExtensionApi}. * * @param extensionApi the {@link ExtensionApi} this extension will use */ protected Extension(@NonNull final ExtensionApi extensionApi) { this.extensionApi = extensionApi; } /** * Get extension name for use by the event hub to managing shared state and for logging. This * MUST be overridden by the extension. If null or empty string is returned, the extension will * not be registered. * * @return the extension name as a {@link String} */ protected abstract @NonNull String getName(); /** * Get friendly, human-readable name of the extension. * * @return the friendly extension name as a {@link String} */ protected @Nullable String getFriendlyName() { return null; } /** * Get extension version as a string for use by the event hub for logging. * * @return the extension version as a {@link String} */ protected @Nullable String getVersion() { return null; } /** * Optional metadata provided for use by the event hub for logging. * * @return the extension metadata as a {@code Map<String, String>} */ protected @Nullable Map<String, String> getMetadata() { return null; } /** * Called when the extension is registered by the core. Implementers can implement this method * to setup event listeners and shared states. */ protected void onRegistered() { Log.trace(CoreConstants.LOG_TAG, getLogTag(), "Extension registered successfully."); } /** * Called when the extension is unregistered by the core. Implementers can implement this method * to clean up resources when the extension is released. */ protected void onUnregistered() { Log.trace(CoreConstants.LOG_TAG, getLogTag(), "Extension unregistered successfully."); } /** * Called before each Event is processed by any ExtensionListener owned by this Extension Should * be overridden by any extension that wants to control its own Event flow on a per Event basis. * * @param event {@link Event} that will be processed next * @return {@code boolean} to denote if event processing should continue for this `Extension` */ public boolean readyForEvent(@NonNull final Event event) { return true; } /** * This provides the services the extension will need. * * @return the {@link ExtensionApi} used to handle this extension */ public final @NonNull ExtensionApi getApi() { return extensionApi; } /** * Get the log tag for this extension. * * @return a log tag for this extension */ private String getLogTag() { return "Extension[" + getName() + "(" + getVersion() + ")]"; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/SharedStateResolution.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; /** Type representing the resolution of an extension's `SharedState` */ public enum SharedStateResolution { /** LAST_SET will resolve for the last set shared state */ LAST_SET, /** ANY will resolve for the last shared state indiscriminately */ ANY, }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/ExtensionApi.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.Map; /** * Class that defines all the public methods an {@code Extension} may call to interface with the AEP * SDK. */ public abstract class ExtensionApi { /** * Registers a new event listener for current extension for the provided event type and source. * * @param eventType required parameter, the event type as a valid string (not null or empty) * @param eventSource required parameter, the event source as a valid string (not null or empty) * @param eventListener required parameter, the listener which extends the {@link * ExtensionEventListener} interface */ public abstract void registerEventListener( @NonNull final String eventType, @NonNull final String eventSource, @NonNull final ExtensionEventListener eventListener); /** * Dispatches an `Event` to the `EventHub` * * @param event An Event to be dispatched to the {@code EventHub} */ public abstract void dispatch(@NonNull final Event event); /** Starts the `Event` queue for this extension */ public abstract void startEvents(); /** Stops the `Event` queue for this extension */ public abstract void stopEvents(); // Shared state /** * Creates a new shared state for this extension. If event is null, one of two behaviors will be * observed: * * <ul> * <li>If this extension has not previously published a shared state, shared state will be * versioned at 0 * <li>If this extension has previously published a shared state, shared state will be * versioned at the latest * </ul> * * @param state {@code Map<String, Object>} representing current state of this extension * @param event The {@link Event} for which the state is being set. Passing null will set the * state for the next shared state version */ public abstract void createSharedState( @NonNull final Map<String, Object> state, @Nullable final Event event); /** * Creates a pending shared state for this extension. * * <ul> * <li>If this extension has not previously published a shared state, shared state will be * versioned at 0 * <li>If this extension has previously published a shared state, shared state will be * versioned at the latest * </ul> * * @param event The {@link Event} for which pending shared state is being set. Passing null will * set the state for the next shared state version. * @return {@link SharedStateResolver} that should be called with the shared state data when it * is ready */ public abstract @Nullable SharedStateResolver createPendingSharedState( @Nullable final Event event); /** * Gets the shared state data for a specified extension. * * @param extensionName extension name for which to retrieve data. See documentation for the * list of available states. * @param event the {@link Event} for which the state is being requested. Passing null will * retrieve latest state available. * @param barrier If true, the {@code EventHub} will only return {@code set} if extensionName * has moved past event. * @param resolution the {@link SharedStateResolution} to resolve for return {@code * SharedStateResult} for the requested extensionName and event */ public abstract @Nullable SharedStateResult getSharedState( @NonNull final String extensionName, @Nullable final Event event, final boolean barrier, @NonNull final SharedStateResolution resolution); // XDM Shared state /** * Creates a new XDM shared state for this extension. The state passed to this API needs to be * mapped to known XDM mixins. If an extension uses multiple mixins, the current data for all of * them should be provided when the XDM shared state is set. If event is null, one of two * behaviors will be observed: * * <ul> * <li>If this extension has not previously published a shared state, shared state will be * versioned at 0 * <li>If this extension has previously published a shared state, shared state will be * versioned at the latest * </ul> * * @param state {@code Map<String, Object>} representing current state of this extension * @param event The {@link Event} for which the state is being set. Passing null will set the * state for the next shared state version */ public abstract void createXDMSharedState( @NonNull final Map<String, Object> state, @Nullable final Event event); /** * Creates a pending XDM shared state for this extension. * * <ul> * <li>If this extension has not previously published a shared state, shared state will be * versioned at 0 * <li>If this extension has previously published a shared state, shared state will be * versioned at the latest * </ul> * * @param event The {@link Event} for which pending shared state is being set. Passing null will * set the state for the next shared state version. * @return {@link SharedStateResolver} that should be called with the shared state data when it * is ready */ public abstract @Nullable SharedStateResolver createPendingXDMSharedState( @Nullable final Event event); /** * Gets the XDM shared state data for a specified extension. If the stateName extension * populates multiple mixins in their shared state, all the data will be returned at once and it * can be accessed using path discovery. * * @param extensionName extension name for which to retrieve data. See documentation for the * list of available states. * @param event the {@link Event} for which the state is being requested. Passing null will * retrieve latest state available. * @param barrier If true, the {@code EventHub} will only return {@code set} if extensionName * has moved past event. * @param resolution the {@link SharedStateResolution} to resolve for return {@code * SharedStateResult} for the requested extensionName and event */ public abstract @Nullable SharedStateResult getXDMSharedState( @NonNull final String extensionName, @Nullable final Event event, final boolean barrier, @NonNull final SharedStateResolution resolution); /** * Unregisters current extension. <br> * This method executes asynchronously, unregistering the extension on the event hub thread. * {@link Extension#onUnregistered} method will be called at the end of this operation. * * @see Extension#onUnregistered() */ public abstract void unregisterExtension(); /** * Retrieves a count of historical events matching the provided requests. * * @param eventHistoryRequests an array of {@link EventHistoryRequest}s used to generate the * hash and timeframe for the event lookup * @param enforceOrder if `true`, consecutive lookups will use the oldest timestamp from the * previous event as their from date * @param handler the {@link EventHistoryResultHandler} for each provided request */ public abstract void getHistoricalEvents( @NonNull EventHistoryRequest[] eventHistoryRequests, boolean enforceOrder, @NonNull EventHistoryResultHandler<Integer> handler); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/MobileCore.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import android.app.Activity; import android.app.Application; import android.app.Application.ActivityLifecycleCallbacks; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.core.os.UserManagerCompat; import com.adobe.marketing.mobile.internal.AppResourceStore; import com.adobe.marketing.mobile.internal.CoreConstants; import com.adobe.marketing.mobile.internal.DataMarshaller; import com.adobe.marketing.mobile.internal.configuration.ConfigurationExtension; import com.adobe.marketing.mobile.internal.eventhub.EventHub; import com.adobe.marketing.mobile.internal.eventhub.EventHubConstants; import com.adobe.marketing.mobile.internal.migration.V4Migrator; import com.adobe.marketing.mobile.services.Log; import com.adobe.marketing.mobile.services.ServiceProvider; import com.adobe.marketing.mobile.services.internal.context.App; import com.adobe.marketing.mobile.util.DataReader; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public final class MobileCore { private static final String LOG_TAG = "MobileCore"; private static final long API_TIMEOUT_MS = 5000; static AtomicBoolean sdkInitializedWithContext = new AtomicBoolean(false); private MobileCore() {} // ======================================================== // MobileCore methods // ======================================================== /** * Returns the version for the {@code MobileCore} extension * * @return The version string */ @NonNull public static String extensionVersion() { WrapperType wrapperType = EventHub.Companion.getShared().getWrapperType(); if (wrapperType == WrapperType.NONE) { return EventHubConstants.VERSION_NUMBER; } else { return EventHubConstants.VERSION_NUMBER + "-" + wrapperType.getWrapperTag(); } } /** * Sets the SDK's current wrapper type. This API should only be used if being developed on * platforms such as React Native or Flutter * * <p> * * @param wrapperType the type of wrapper being used. It should not be null. */ public static void setWrapperType(@NonNull final WrapperType wrapperType) { if (wrapperType == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "setWrapperType failed - wrapperType is null."); return; } EventHub.Companion.getShared().setWrapperType(wrapperType); } /** * Set the Android {@link Application}, which enables the SDK get the app {@code Context}, * register a {@link ActivityLifecycleCallbacks} to monitor the lifecycle of the app and get the * {@link Activity} on top of the screen. * * <p>NOTE: This method should be called right after the app starts, so it gives the SDK all the * contexts it needed. * * @param application the Android {@link Application} instance. It should not be null. */ public static void setApplication(@NonNull final Application application) { if (application == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "setApplication failed - application is null"); return; } // Direct boot mode is supported on Android N and above if (VERSION.SDK_INT >= VERSION_CODES.N) { if (UserManagerCompat.isUserUnlocked(application)) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "setApplication - device is unlocked and not in direct boot mode," + " initializing the SDK."); } else { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "setApplication failed - device is in direct boot mode, SDK will not be" + " initialized."); return; } } if (sdkInitializedWithContext.getAndSet(true)) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "setApplication failed - ignoring as setApplication was already called."); return; } if (VERSION.SDK_INT == VERSION_CODES.O || VERSION.SDK_INT == VERSION_CODES.O_MR1) { // AMSDK-8502 // Workaround to prevent a crash happening on Android 8.0/8.1 related to // TimeZoneNamesImpl // https://issuetracker.google.com/issues/110848122 try { new Date().toString(); } catch (AssertionError e) { // Workaround for a bug in Android that can cause crashes on Android 8.0 and 8.1 } catch (Exception e) { // Workaround for a bug in Android that can cause crashes on Android 8.0 and 8.1 } } ServiceProvider.getInstance().getAppContextService().setApplication(application); App.INSTANCE.registerActivityResumedListener(MobileCore::collectLaunchInfo); // Migration and EventHistory operations must complete in a background thread before any // extensions are registered. // To ensure these tasks are completed before any registerExtension calls are made, // reuse the eventHubExecutor instead of using a separate executor instance. EventHub.Companion.getShared() .executeInEventHubExecutor( () -> { try { V4Migrator migrator = new V4Migrator(); migrator.migrate(); } catch (Exception e) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "Migration from V4 SDK failed with error - " + e.getLocalizedMessage()); } // Initialize event history EventHub.Companion.getShared().initializeEventHistory(); return null; }); } /** * Get the global {@link Application} object of the current process. * * <p>NOTE: {@link #setApplication(Application)} must be called before calling this method. * * @return the current {@code Application}, or null if no {@code Application} was set or the * {@code Application} process was destroyed. */ @Nullable public static Application getApplication() { return ServiceProvider.getInstance().getAppContextService().getApplication(); } /** * Set the {@link LoggingMode} level for the Mobile SDK. * * @param mode the logging mode. It should not be null. */ public static void setLogLevel(@NonNull final LoggingMode mode) { if (mode == null) { Log.error(CoreConstants.LOG_TAG, LOG_TAG, "setLogLevel failed - mode is null"); return; } com.adobe.marketing.mobile.services.Log.setLogLevel(mode); } /** * Get the {@link LoggingMode} level for the Mobile SDK * * @return the set {@code LoggingMode} */ @NonNull public static LoggingMode getLogLevel() { return com.adobe.marketing.mobile.services.Log.getLogLevel(); } /** * Registers all extensions with Core and starts event processing. * * <p>This method needs to be called after {@link MobileCore#setApplication(Application)} is * called. * * @param extensions List of extension classes whose parent is {@link Extension}. It should not * be null. * @param completionCallback an optional {@link AdobeCallback} invoked after registrations are * completed */ public static void registerExtensions( @NonNull final List<Class<? extends Extension>> extensions, @Nullable final AdobeCallback<?> completionCallback) { if (!sdkInitializedWithContext.get()) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "Failed to registerExtensions - setApplication not called"); return; } final List<Class<? extends Extension>> extensionsToRegister = new ArrayList<>(); extensionsToRegister.add(ConfigurationExtension.class); if (extensions != null) { for (final Class<? extends Extension> extension : extensions) { if (extension != null) { extensionsToRegister.add(extension); } } } final AtomicInteger registeredExtensions = new AtomicInteger(0); for (final Class<? extends Extension> extension : extensionsToRegister) { EventHub.Companion.getShared() .registerExtension( extension, eventHubError -> { if (registeredExtensions.incrementAndGet() == extensionsToRegister.size()) { EventHub.Companion.getShared().start(); try { if (completionCallback != null) { completionCallback.call(null); } } catch (Exception ex) { } } return null; }); } } /** * Registers an event listener for the provided event type and source. * * @param eventType the event type as a valid string. It should not be null or empty. * @param eventSource the event source as a valid string. It should not be null or empty. * @param callback the callback whose {@link AdobeCallback#call(Object)} will be called when the * event is heard. It should not be null. */ public static void registerEventListener( @NonNull final String eventType, @NonNull final String eventSource, @NonNull final AdobeCallback<Event> callback) { if (callback == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "Failed to registerEventListener - callback is null", Log.UNEXPECTED_NULL_VALUE); return; } if (eventType == null || eventSource == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "Failed to registerEventListener - event type/source is null"); return; } EventHub.Companion.getShared().registerListener(eventType, eventSource, callback); } /** * This method will dispatch the provided {@code Event} to dispatch an event for other * extensions or the internal SDK to consume. * * @param event the {@link Event} to be dispatched. It should not be null */ public static void dispatchEvent(@NonNull final Event event) { if (event == null) { Log.error(CoreConstants.LOG_TAG, LOG_TAG, "Failed to dispatchEvent - event is null"); return; } EventHub.Companion.getShared().dispatch(event); } /** * This method will be used when the provided {@code Event} is used as a trigger and a response * event is expected in return. * * <p>Passes an {@link AdobeError#UNEXPECTED_ERROR} to {@link * AdobeCallbackWithError#fail(AdobeError)} if {@code event} is null. Passes an {@link * AdobeError#CALLBACK_TIMEOUT} to {@link AdobeCallbackWithError#fail(AdobeError)} if {@code * event} processing timeout occurs. * * @param event the {@link Event} to be dispatched, used as a trigger. It should not be null. * @param timeoutMS the timeout specified in milliseconds. * @param responseCallback the callback whose {@link AdobeCallbackWithError#call(Object)} will * be called when the response event is heard. It should not be null. */ public static void dispatchEventWithResponseCallback( @NonNull final Event event, final long timeoutMS, @NonNull final AdobeCallbackWithError<Event> responseCallback) { if (responseCallback == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "Failed to dispatchEventWithResponseCallback - callback is null"); return; } if (event == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "Failed to dispatchEventWithResponseCallback - event is null"); responseCallback.fail(AdobeError.UNEXPECTED_ERROR); return; } EventHub.Companion.getShared().registerResponseListener(event, timeoutMS, responseCallback); EventHub.Companion.getShared().dispatch(event); } /** * Sets the resource Id for small icon. * * @param resourceID the resource Id of the icon */ public static void setSmallIconResourceID(final int resourceID) { AppResourceStore.INSTANCE.setSmallIconResourceID(resourceID); } /** * Returns the resource Id for small icon if it was set by `setSmallIconResourceID`. * * @return a `int` value if it has been set, otherwise -1 */ public static int getSmallIconResourceID() { return AppResourceStore.INSTANCE.getSmallIconResourceID(); } /** * Sets the resource Id for large icon. * * @param resourceID the resource Id of the icon */ public static void setLargeIconResourceID(final int resourceID) { AppResourceStore.INSTANCE.setLargeIconResourceID(resourceID); } /** * Returns the resource Id for large icon if it was set by `setLargeIconResourceID`. * * @return a `int` value if it has been set, otherwise -1 */ public static int getLargeIconResourceID() { return AppResourceStore.INSTANCE.getLargeIconResourceID(); } // ======================================================== // Identifiers // ======================================================== /** * This method dispatches an event to notify the SDK of a new {@code advertisingIdentifier} * * @param advertisingIdentifier {@code String} representing Android advertising identifier */ public static void setAdvertisingIdentifier(@Nullable final String advertisingIdentifier) { Map<String, Object> eventData = new HashMap<>(); eventData.put( CoreConstants.EventDataKeys.Identity.ADVERTISING_IDENTIFIER, advertisingIdentifier); Event event = new Event.Builder( CoreConstants.EventNames.SET_ADVERTISING_IDENTIFIER, EventType.GENERIC_IDENTITY, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } /** * This method dispatches an event to notify the SDK of a new {@code pushIdentifier} * * @param pushIdentifier {@code String} representing the new push identifier */ public static void setPushIdentifier(@Nullable final String pushIdentifier) { Map<String, Object> eventData = new HashMap<>(); eventData.put(CoreConstants.EventDataKeys.Identity.PUSH_IDENTIFIER, pushIdentifier); Event event = new Event.Builder( CoreConstants.EventNames.SET_PUSH_IDENTIFIER, EventType.GENERIC_IDENTITY, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } /** * Collect PII data. Although using this call enables collection of PII data, the SDK does not * automatically send the data to any Adobe endpoint. * * @param data the map containing the PII data to be collected. It should not be null or empty. */ public static void collectPii(@NonNull final Map<String, String> data) { if (data == null || data.isEmpty()) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "Could not trigger PII, the data is null or empty."); return; } final Map<String, Object> eventData = new HashMap<>(); eventData.put(CoreConstants.EventDataKeys.Signal.SIGNAL_CONTEXT_DATA, data); Event event = new Event.Builder( CoreConstants.EventNames.COLLECT_PII, EventType.GENERIC_PII, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } /** * Collects message data from various points in the application. * * <p>This method can be invoked to support the following use cases: * * <ol> * <li>Tracking Push Message receive and click. * <li>Tracking Local Notification receive and click. * </ol> * * <p>The message tracking information can be supplied in the {@code messageInfo} Map. For * scenarios where the application is launched as a result of notification click, {@link * #collectLaunchInfo(Activity)} will be invoked with the target Activity and message data will * be extracted from the Intent extras. * * @param messageInfo {@code Map<String, Object>} containing message tracking information. It * should not be null or empty. */ public static void collectMessageInfo(@NonNull final Map<String, Object> messageInfo) { if (messageInfo == null || messageInfo.isEmpty()) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "collectData: Could not dispatch generic data event, data is null or empty."); return; } Event event = new Event.Builder( CoreConstants.EventNames.COLLECT_DATA, EventType.GENERIC_DATA, EventSource.OS) .setEventData(messageInfo) .build(); dispatchEvent(event); } /** * Collects data from the Activity / context to be used later by the SDK. * * <p>This method marshals the {@code activity} instance and extracts the intent data / extras. * * <ol> * <li>Tracking Deep Link click-through * <ul> * <li>Update AndroidManifest.xml to support intent-filter in the activity with the * intended action and type of data. * <li>Handle the intent in the activity. * </ul> * <li>Tracking Push Message click-through * <li>Tracking Local Notification click-through * </ol> * * <p>Invoke this method from Activity.onResume() callback in your activity. * * @param activity current {@link Activity} reference. */ @VisibleForTesting static void collectLaunchInfo(final Activity activity) { final Map<String, Object> marshalledData = DataMarshaller.marshal(activity); if (marshalledData == null || marshalledData.isEmpty()) { Log.debug( CoreConstants.LOG_TAG, LOG_TAG, "collectData: Could not dispatch generic data event, data is null or empty."); return; } Event event = new Event.Builder( CoreConstants.EventNames.COLLECT_DATA, EventType.GENERIC_DATA, EventSource.OS) .setEventData(marshalledData) .build(); dispatchEvent(event); } // ======================================================== // Configuration methods // ======================================================== /** * Configure the SDK by downloading the remote configuration file hosted on Adobe servers * specified by the given application ID. * * <p>The configuration file is cached once downloaded and used in subsequent calls to this API. * If the remote file is updated after the first download, the updated file is downloaded and * replaces the cached file. * * @param appId A unique identifier assigned to the app instance by Adobe Launch. It should not * be null. */ public static void configureWithAppID(@NonNull final String appId) { if (appId == null) { Log.error(CoreConstants.LOG_TAG, LOG_TAG, "configureWithAppID failed - appId is null."); return; } Map<String, Object> eventData = new HashMap<>(); eventData.put( CoreConstants.EventDataKeys.Configuration.CONFIGURATION_REQUEST_CONTENT_JSON_APP_ID, appId); Event event = new Event.Builder( CoreConstants.EventNames.CONFIGURE_WITH_APP_ID, EventType.CONFIGURATION, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } /** * Load configuration from the file in the assets folder. SDK automatically reads config from * `ADBMobileConfig.json` file if it exists in the assets folder. Use this API only if the * config needs to be read from a different file. * * <p>On application relaunch, the configuration from the file at {@code filepath} is not * preserved and this method must be called again if desired. * * <p>On failure to read the file or parse the JSON contents, the existing configuration remains * unchanged. * * <p>Calls to this API will replace any existing SDK configuration except those set using * {@link #updateConfiguration(Map)} or {@link #setPrivacyStatus(MobilePrivacyStatus)}. * Configuration updates made using {@link #updateConfiguration(Map)} and {@link * #setPrivacyStatus(MobilePrivacyStatus)} are always applied on top of configuration changes * made using this API. * * @param fileName the name of the configure file in the assets folder. It should not be null. */ public static void configureWithFileInAssets(@NonNull final String fileName) { if (fileName == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "configureWithFileInAssets failed - fileName is null."); return; } Map<String, Object> eventData = new HashMap<>(); eventData.put( CoreConstants.EventDataKeys.Configuration .CONFIGURATION_REQUEST_CONTENT_JSON_ASSET_FILE, fileName); Event event = new Event.Builder( CoreConstants.EventNames.CONFIGURE_WITH_FILE_PATH, EventType.CONFIGURATION, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } /** * Load configuration from local file. * * <p>Configure the SDK by reading a local file containing the JSON configuration. On * application relaunch, the configuration from the file at {@code filepath} is not preserved * and this method must be called again if desired. * * <p>On failure to read the file or parse the JSON contents, the existing configuration remains * unchanged. * * <p>Calls to this API will replace any existing SDK configuration except those set using * {@link #updateConfiguration(Map)} or {@link #setPrivacyStatus(MobilePrivacyStatus)}. * Configuration updates made using {@link #updateConfiguration(Map)} and {@link * #setPrivacyStatus(MobilePrivacyStatus)} are always applied on top of configuration changes * made using this API. * * @param filePath absolute path to a local configuration file. It should not be null. */ public static void configureWithFileInPath(@NonNull final String filePath) { if (filePath == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "configureWithFileInPath failed - filePath is null."); return; } Map<String, Object> eventData = new HashMap<>(); eventData.put( CoreConstants.EventDataKeys.Configuration .CONFIGURATION_REQUEST_CONTENT_JSON_FILE_PATH, filePath); Event event = new Event.Builder( CoreConstants.EventNames.CONFIGURE_WITH_FILE_PATH, EventType.CONFIGURATION, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } /** * Update specific configuration parameters. * * <p>Update the current SDK configuration with specific key/value pairs. Keys not found in the * current configuration are added. Configuration updates are preserved and applied over * existing or new configurations set by calling {@link #configureWithAppID(String)} or {@link * #configureWithFileInPath(String)}, even across application restarts. * * <p>Using {@code null} values is allowed and effectively removes the configuration parameter * from the current configuration. * * @param configMap configuration key/value pairs to be updated or added. It should not be null. */ public static void updateConfiguration(@NonNull final Map<String, Object> configMap) { if (configMap == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "updateConfiguration failed - configMap is null."); return; } Map<String, Object> eventData = new HashMap<>(); eventData.put( CoreConstants.EventDataKeys.Configuration .CONFIGURATION_REQUEST_CONTENT_UPDATE_CONFIG, configMap); Event event = new Event.Builder( CoreConstants.EventNames.CONFIGURATION_UPDATE, EventType.CONFIGURATION, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } /** * Clear the changes made by {@link #updateConfiguration(Map)} and {@link * #setPrivacyStatus(MobilePrivacyStatus)} to the initial configuration provided either by * {@link #configureWithAppID(String)} or {@link #configureWithFileInPath(String)} or {@link * #configureWithFileInAssets(String)} */ public static void clearUpdatedConfiguration() { Map<String, Object> eventData = new HashMap<>(); eventData.put( CoreConstants.EventDataKeys.Configuration .CONFIGURATION_REQUEST_CONTENT_CLEAR_UPDATED_CONFIG, true); Event event = new Event.Builder( CoreConstants.EventNames.CLEAR_UPDATED_CONFIGURATION, EventType.CONFIGURATION, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } /** * Set the Adobe Mobile Privacy status. * * <p>Sets the {@link MobilePrivacyStatus} for this SDK. The set privacy status is preserved and * applied over any new configuration changes from calls to {@link #configureWithAppID(String)} * or {@link #configureWithFileInPath(String)}, even across application restarts. * * @param privacyStatus {@link MobilePrivacyStatus} to be set to the SDK * @see MobilePrivacyStatus */ public static void setPrivacyStatus(@NonNull final MobilePrivacyStatus privacyStatus) { if (privacyStatus == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "setPrivacyStatus failed - privacyStatus is null."); return; } Map<String, Object> privacyStatusUpdateConfig = new HashMap<>(); privacyStatusUpdateConfig.put( CoreConstants.EventDataKeys.Configuration.GLOBAL_CONFIG_PRIVACY, privacyStatus.getValue()); updateConfiguration(privacyStatusUpdateConfig); } /** * Get the current Adobe Mobile Privacy Status. * * <p>Gets the currently configured {@link MobilePrivacyStatus} and passes it as a parameter to * the given {@link AdobeCallback#call(Object)} function. * * @param callback {@link AdobeCallback} instance which is invoked with the configured privacy * status as a parameter. It should not be null. * @see AdobeCallback * @see MobilePrivacyStatus */ public static void getPrivacyStatus(final AdobeCallback<MobilePrivacyStatus> callback) { if (callback == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "Failed to retrieve the privacy status - callback is null"); return; } Map<String, Object> eventData = new HashMap<>(); eventData.put( CoreConstants.EventDataKeys.Configuration .CONFIGURATION_REQUEST_CONTENT_RETRIEVE_CONFIG, true); Event event = new Event.Builder( CoreConstants.EventNames.PRIVACY_STATUS_REQUEST, EventType.CONFIGURATION, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); AdobeCallbackWithError<Event> callbackWithError = new AdobeCallbackWithError<Event>() { @Override public void fail(final AdobeError error) { if (callback instanceof AdobeCallbackWithError) { ((AdobeCallbackWithError<?>) callback) .fail(AdobeError.CALLBACK_TIMEOUT); } else { // Todo - Check if this is a valid return value. callback.call(null); } } @Override public void call(final Event event) { String status = DataReader.optString( event.getEventData(), CoreConstants.EventDataKeys.Configuration .GLOBAL_CONFIG_PRIVACY, null); callback.call(MobilePrivacyStatus.fromString(status)); } }; dispatchEventWithResponseCallback(event, API_TIMEOUT_MS, callbackWithError); } /** * Retrieve all identities stored by/known to the SDK in a JSON {@code String} format. * * @param callback {@link AdobeCallback} instance which is invoked with all the known identifier * in JSON {@link String} format. It should not be null. * @see AdobeCallback */ public static void getSdkIdentities(@NonNull final AdobeCallback<String> callback) { if (callback == null) { Log.error( CoreConstants.LOG_TAG, LOG_TAG, "Failed to get SDK identities - callback is null"); return; } AdobeCallbackWithError<Event> callbackWithError = new AdobeCallbackWithError<Event>() { @Override public void fail(final AdobeError error) { if (callback instanceof AdobeCallbackWithError) { ((AdobeCallbackWithError<?>) callback) .fail(AdobeError.CALLBACK_TIMEOUT); } else { callback.call("{}"); } } @Override public void call(final Event event) { String value = DataReader.optString( event.getEventData(), CoreConstants.EventDataKeys.Configuration .CONFIGURATION_RESPONSE_IDENTITY_ALL_IDENTIFIERS, "{}"); callback.call(value); } }; Event event = new Event.Builder( CoreConstants.EventNames.GET_SDK_IDENTITIES, EventType.CONFIGURATION, EventSource.REQUEST_IDENTITY) .build(); dispatchEventWithResponseCallback(event, API_TIMEOUT_MS, callbackWithError); } /** * Clears all identifiers from Edge extensions and generates a new Experience Cloud ID (ECID). */ public static void resetIdentities() { Event event = new Event.Builder( CoreConstants.EventNames.RESET_IDENTITIES_REQUEST, EventType.GENERIC_IDENTITY, EventSource.REQUEST_RESET) .build(); dispatchEvent(event); } // ======================================================== // Lifecycle methods // ======================================================== /** * Start/resume lifecycle session. * * <p>Start a new lifecycle session or resume a previously paused lifecycle session. If a * previously paused session timed out, then a new session is created. If a current session is * running, then calling this method does nothing. * * <p>Additional context data may be passed when calling this method. Lifecycle data and any * additional data are sent as context data parameters to Analytics, to Target as mbox * parameters, and for Audience Manager they are sent as customer variables. Any additional data * is also used by the Rules Engine when processing rules. * * <p>This method should be called from the Activity onResume method. * * @param additionalContextData optional additional context for this session. */ public static void lifecycleStart(@Nullable final Map<String, String> additionalContextData) { Map<String, Object> eventData = new HashMap<>(); eventData.put( CoreConstants.EventDataKeys.Lifecycle.LIFECYCLE_ACTION_KEY, CoreConstants.EventDataKeys.Lifecycle.LIFECYCLE_START); eventData.put( CoreConstants.EventDataKeys.Lifecycle.ADDITIONAL_CONTEXT_DATA, additionalContextData); Event event = new Event.Builder( CoreConstants.EventNames.LIFECYCLE_RESUME, EventType.GENERIC_LIFECYCLE, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } /** * Pause/stop lifecycle session. * * <p>Pauses the current lifecycle session. Calling pause on an already paused session updates * the paused timestamp, having the effect of resetting the session timeout timer. If no * lifecycle session is running, then calling this method does nothing. * * <p>A paused session is resumed if {@link #lifecycleStart(Map)} is called before the session * timeout. After the session timeout, a paused session is closed and calling {@link * #lifecycleStart(Map)} will create a new session. The session timeout is defined by the {@code * lifecycle.sessionTimeout} configuration parameter. If not defined, the default session * timeout is five minutes. * * <p>This method should be called from the Activity onPause method. */ public static void lifecyclePause() { Map<String, Object> eventData = new HashMap<>(); eventData.put( CoreConstants.EventDataKeys.Lifecycle.LIFECYCLE_ACTION_KEY, CoreConstants.EventDataKeys.Lifecycle.LIFECYCLE_PAUSE); Event event = new Event.Builder( CoreConstants.EventNames.LIFECYCLE_PAUSE, EventType.GENERIC_LIFECYCLE, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } // ======================================================== // Track methods // ======================================================== /** * This method dispatches an Analytics track {@code action} event * * <p>Actions represent events that occur in your application that you want to measure; the * corresponding metrics will be incremented each time the event occurs. For example, you may * want to track when an user click on the login button or a certain article was viewed. * * <p> * * @param action {@code String} containing the name of the action to track * @param contextData {@code Map<String, String>} containing context data to attach on this hit */ public static void trackAction( @NonNull final String action, @Nullable final Map<String, String> contextData) { Map<String, Object> eventData = new HashMap<>(); eventData.put( CoreConstants.EventDataKeys.Analytics.TRACK_ACTION, action == null ? "" : action); eventData.put( CoreConstants.EventDataKeys.Analytics.CONTEXT_DATA, contextData == null ? new HashMap<String, String>() : contextData); Event event = new Event.Builder( CoreConstants.EventNames.ANALYTICS_TRACK, EventType.GENERIC_TRACK, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } /** * This method dispatches an Analytics track {@code state} event * * <p>States represent different screens or views of your application. When the user navigates * between application pages, a new track call should be sent with current state name. Tracking * state name is typically called from an Activity in the onResume method. * * <p> * * @param state {@code String} containing the name of the state to track. It should not be null. * @param contextData optional contextData {@code Map<String, String>} containing context data * to attach on this hit */ public static void trackState( @NonNull final String state, @Nullable final Map<String, String> contextData) { Map<String, Object> eventData = new HashMap<>(); eventData.put( CoreConstants.EventDataKeys.Analytics.TRACK_STATE, state == null ? "" : state); eventData.put( CoreConstants.EventDataKeys.Analytics.CONTEXT_DATA, contextData == null ? new HashMap<String, String>() : contextData); Event event = new Event.Builder( CoreConstants.EventNames.ANALYTICS_TRACK, EventType.GENERIC_TRACK, EventSource.REQUEST_CONTENT) .setEventData(eventData) .build(); dispatchEvent(event); } @VisibleForTesting static void resetSDK() { EventHub.Companion.getShared().shutdown(); EventHub.Companion.setShared(new EventHub()); sdkInitializedWithContext.set(false); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/EventHistoryRequest.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import com.adobe.marketing.mobile.internal.util.MapUtilsKt; import java.util.Map; public class EventHistoryRequest { private final Map<String, Object> map; private final long fromDate; private final long toDate; /** * Used for selecting or deleting Events from Event History. * * @param map Key-value pairs that will be used to generate the hash when looking up an Event. * @param fromDate Date that represents the lower bounds of the date range used when looking up * an Event. If not provided, the lookup will use the beginning of Event History as the * lower bounds. * @param toDate Date that represents the upper bounds of the date range used when looking up an * Event. If not provided, there will be no upper bound on the date range. */ public EventHistoryRequest( final Map<String, Object> map, final long fromDate, final long toDate) { this.map = map; this.fromDate = fromDate; this.toDate = toDate; } public long getMaskAsDecimalHash() { return MapUtilsKt.convertMapToFnv1aHash(map, null); } public long getFromDate() { return fromDate; } public long getToDate() { return toDate; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/LoggingMode.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; public enum LoggingMode { ERROR(0), WARNING(1), DEBUG(2), VERBOSE(3); public final int id; LoggingMode(final int identifier) { id = identifier; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/EventCoder.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import androidx.annotation.Nullable; import com.adobe.marketing.mobile.util.JSONUtils; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** The helper methods used to encode/decode an Event to/from json String */ public class EventCoder { private static final String NAME = "name"; private static final String UUID = "uuid"; private static final String SOURCE = "source"; private static final String TYPE = "type"; private static final String DATA = "data"; private static final String TIMESTAMP = "timestamp"; private static final String RESPONSE_ID = "responseId"; private static final String PARENT_ID = "parentId"; private static final String MASK = "mask"; private EventCoder() {} /** * Decode an event from json string * * @param eventString the json string * @return the decoded event if the json is valid, otherwise null */ public static Event decode(final String eventString) { if (eventString == null) { return null; } try { final JSONObject json = new JSONObject(eventString); final String name = optString(json, NAME, null); final String uniqueIdentifier = optString(json, UUID, null); final String source = optString(json, SOURCE, null); final String type = optString(json, TYPE, null); final Map<String, Object> data = JSONUtils.toMap(json.optJSONObject(DATA)); final long timestamp = json.optLong(TIMESTAMP, 0); final String responseId = optString(json, RESPONSE_ID, null); final String parentId = optString(json, PARENT_ID, null); final JSONArray maskJsonArray = json.optJSONArray(MASK); String[] mask = null; if (maskJsonArray != null) { mask = JSONUtils.toList(maskJsonArray).toArray(new String[0]); } final Event ret = new Event.Builder(name, type, source, mask) .setUniqueIdentifier(uniqueIdentifier) .setTimestamp(timestamp) .setEventData(data) .setResponseId(responseId) .setParentId(parentId) .build(); return ret; } catch (JSONException e) { return null; } } /** * Encode an event to a json string * * @param event the event to encode * @return json string represents all the fields of the event, otherwise returns null if the * event is null or there is json error */ public static String encode(final Event event) { if (event == null) { return null; } JSONObject json = new JSONObject(); try { json.put(NAME, event.getName()); json.put(TYPE, event.getType()); json.put(SOURCE, event.getSource()); json.put(UUID, event.getUniqueIdentifier()); json.put(TIMESTAMP, event.getTimestamp()); json.put(DATA, JSONObject.wrap(event.getEventData())); json.put(RESPONSE_ID, event.getResponseID()); json.put(PARENT_ID, event.getParentID()); json.put(MASK, JSONObject.wrap(event.getMask())); } catch (JSONException e) { return null; } return json.toString(); } /** * Returns the value mapped by {@code key} if it exists, or the {@code fallback} if no such * mapping exists. Exists because {@code JSONObject#optString} does not allow a null fallback. * * @param jsonObject the json from which the key is to be fetched * @param key the key that is to be fetched * @param fallback the fallback value if the key does not exist in {@code jsonObject} * @return value mapped by {@code key} if it exists in {@code jsonObject}, or {@code fallback} * if no such mapping exists. */ private static String optString( final JSONObject jsonObject, final String key, @Nullable final String fallback) { try { return jsonObject.getString(key); } catch (final JSONException e) { return fallback; } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/SharedStateResult.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.Map; /** Contains the status and value for a given shared state */ public class SharedStateResult { private final SharedStateStatus status; private final Map<String, Object> value; /** * Creates a new shared state result with given status and value * * @param status status of the shared state * @param value value of the shared state */ public SharedStateResult( @NonNull final SharedStateStatus status, @Nullable final Map<String, Object> value) { this.status = status; this.value = value; } /** Returns the {@link SharedStateStatus}. */ public @NonNull SharedStateStatus getStatus() { return status; } /** Returns the shared state. */ public @Nullable Map<String, Object> getValue() { return value; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/ExtensionEventListener.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import androidx.annotation.NonNull; /** * Defines a generic listener that can hear a specific kind of {@code Event} on an {@code EventHub} */ @FunctionalInterface public interface ExtensionEventListener { void hear(@NonNull final Event event); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/MobilePrivacyStatus.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; /** * Represents the possible privacy settings for the Adobe SDK. * * <p>The possible values for the Adobe Mobile Privacy Status. The privacy status controls whether * specific activity is allowed on the device. The default privacy status is set in any ADBMobile * JSON configuration file using the parameter {@code global.privacy}. Use {@code * AdobeMobileMarketing.setPrivacyStatus()} API to override the default privacy status. * * <p>(TODO - verify the documentation link is accurate for AMSDK V5) To learn more about the Adobe * Mobile Privacy Status, view the online documentation at <a * href="https://marketing.adobe.com/resources/help/en_US/mobile/ios/privacy.html">https://marketing.adobe.com/resources/help/en_US/mobile/ios/privacy.html</a> */ public enum MobilePrivacyStatus { /** Adobe Mobile Privacy Status opted-in. */ OPT_IN("optedin"), /** Adobe Mobile Privacy Status opted-out. */ OPT_OUT("optedout"), /** Adobe Mobile Privacy Status is unknown. */ UNKNOWN("optunknown"); private final String value; MobilePrivacyStatus(final String value) { this.value = value; } /** * Returns the string value for this enum type. * * @return the string name for this enum type. */ public String getValue() { return value; } /** * Returns a {@link MobilePrivacyStatus} object based on the provided {@code text}. * * <p>If the text provided is not valid, {@link #UNKNOWN} will be returned. * * @param text {@link String} to be converted to a {@code MobilePrivacyStatus} object * @return {@code MobilePrivacyStatus} object equivalent to the provided text */ public static MobilePrivacyStatus fromString(final String text) { for (MobilePrivacyStatus b : MobilePrivacyStatus.values()) { if (b.value.equalsIgnoreCase(text)) { return b; } } return UNKNOWN; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/SharedStateResolver.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import androidx.annotation.Nullable; import java.util.Map; /** * A `SharedStateResolver` which is invoked to set pending the `SharedState` versioned at `Event` */ @FunctionalInterface public interface SharedStateResolver { /** * @param state A {@code Map<String, Object>} containing data to resolve pending shared state. */ void resolve(@Nullable final Map<String, Object> state); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/Event.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import androidx.annotation.NonNull; import com.adobe.marketing.mobile.internal.CoreConstants; import com.adobe.marketing.mobile.internal.util.MapExtensionsKt; import com.adobe.marketing.mobile.services.Log; import com.adobe.marketing.mobile.util.EventDataUtils; import java.util.*; import java.util.concurrent.TimeUnit; /** * Represents a single event * * @author Adobe Systems Incorporated * @version 5.0 */ public final class Event { // Name of the event private String name; // Unique identifier for the event private String uniqueIdentifier; // The `EventSource` for the event private String source; // The `EventType` for the event private String type; // Optional data associated with this event private Map<String, Object> data; // Time this event was created private long timestamp; // If `responseID` is not nil, then this event is a response event and `responseID` is the // `event.id` of the `triggerEvent` private String responseID; // Represents the unique identifier for the parent of this event. The parent event is a // trigger for creating the current event private String parentID; // Specifies the properties in the Event and its data that should be used in the hash for // EventHistory storage. private String[] mask; /** Event Builder */ public static class Builder { private final Event event; private boolean didBuild; /** * Builder constructor with required {@code Event} attributes as parameters * * @param name required {@code String} to be set as event name; should not be null or empty * string * @param type required {@code String} to be set as event type; should not be null or empty * string * @param source required {@code String} to be set as event source; should not be null or * empty string */ public Builder(final String name, final String type, final String source) { this(name, type, source, null); } /** * Builder constructor with required {@code Event} attributes as parameters * * @param name required {@code String} to be set as event name; should not be null or empty * string * @param type required {@code String} to be set as event type; should not be null or empty * string * @param source required {@code String} to be set as event source; should not be null or * empty string * @param mask {@code String[]} event mask */ public Builder( final String name, final String type, final String source, final String[] mask) { event = new Event(); event.name = name; event.uniqueIdentifier = UUID.randomUUID().toString(); event.type = type; event.source = source; event.responseID = null; event.parentID = null; event.mask = mask; didBuild = false; } /** * Sets the data for this {@code Event}. The keys should be of type {@code String}. * * <p>Note: Custom classes are not supported as value types. These values will be skipped * from the {@code Event} data. * * <p>The accepted value types are: * * <ul> * <li>{@code Boolean} * <li>{@code Byte} * <li>{@code Collection<Object>} * <li>{@code Double} * <li>{@code Float} * <li>{@code Integer} * <li>{@code String} * <li>{@code List<Object>} * <li>{@code Long} * <li>{@code Map<String, Object>} * <li>{@code Short} * <li>null * </ul> * * @param data Data associated with this {@link Event} * @return this Event {@link Builder} * @throws UnsupportedOperationException if this method is called after {@link * Builder#build()} was called */ public Builder setEventData(final Map<String, Object> data) { throwIfAlreadyBuilt(); try { event.data = EventDataUtils.immutableClone(data); } catch (final Exception e) { Log.warning( CoreConstants.LOG_TAG, "EventBuilder", "Event data couldn't be serialized, empty data was set instead %s", e); } return this; } /** * Builds and returns the {@code Event} object. It returns null if the event's type or * source are null * * @return the constructed {@link Event} or null if the type or source are null * @throws UnsupportedOperationException if this method is called again */ public Event build() { throwIfAlreadyBuilt(); didBuild = true; if (event.type == null || event.source == null) { return null; } if (event.timestamp == 0) { event.timestamp = System.currentTimeMillis(); } return event; } /** * Sets the uniqueIdentifier for this {@code Event}. If no unique identifier is set, one is * generated when the {@code Event} is created. * * @param uniqueIdentifier {@code String} event uniqueIdentifier * @return this Event {@link Builder} * @throws UnsupportedOperationException if this method is called after {@link * Builder#build()} was called */ Builder setUniqueIdentifier(final String uniqueIdentifier) { if (uniqueIdentifier == null) { return this; } throwIfAlreadyBuilt(); event.uniqueIdentifier = uniqueIdentifier; return this; } /** * Sets this as response for {@code requestEvent}. Additionally, marks {@code requestEvent} * as the parent event to this event. * * @param requestEvent {@code Event} event * @return this Event {@link Builder} * @throws UnsupportedOperationException if this method is called after {@link * Builder#build()} was called */ public Builder inResponseToEvent(final Event requestEvent) { throwIfAlreadyBuilt(); if (requestEvent == null) { throw new NullPointerException("requestEvent is null"); } setResponseId(requestEvent.uniqueIdentifier); chainToParentEvent(requestEvent); return this; } /** * Sets parent event for this event. * * @param parentEvent the {@code Event} to be set as the parent event. The parent event is * considered as the trigger for creating the current event * @return this {@link Event.Builder} * @throws UnsupportedOperationException if this method is called after {@link * Builder#build()} was called */ public Builder chainToParentEvent(@NonNull final Event parentEvent) { throwIfAlreadyBuilt(); if (parentEvent == null) { throw new NullPointerException("parentEvent cannot be null"); } event.parentID = parentEvent.getUniqueIdentifier(); return this; } /** * Sets responseId for this {@code Event} * * * @param responseId {@code String} event uniqueIdentifier * @return this Event {@link Builder} * @throws UnsupportedOperationException if this method is called after {@link * Builder#build()} was called */ Builder setResponseId(final String responseId) { throwIfAlreadyBuilt(); event.responseID = responseId; return this; } /** * Sets parentId for this event * * @param parentId the uniqueIdentifier of the parent event * @return this {@link Event.Builder} * @throws UnsupportedOperationException if this method is called after {@link * Builder#build()} was called */ Builder setParentId(final String parentId) { throwIfAlreadyBuilt(); event.parentID = parentId; return this; } /** * Set the timestamp for this event * * @param timestamp long event timestamp * @return this Event {@link Builder} * @throws UnsupportedOperationException if this method is called after {@link * Builder#build()} was called */ Builder setTimestamp(final long timestamp) { throwIfAlreadyBuilt(); event.timestamp = timestamp; return this; } private void throwIfAlreadyBuilt() { if (didBuild) { throw new UnsupportedOperationException( "Event - attempted to call methods on Event.Builder after build() was" + " called"); } } } /** Private constructor. Use builder to create an event */ @SuppressWarnings("unused") private Event() {} /** * Clones the current {@link Event} with updated data * * @param newData data associated with the new {@code Event} * @return new cloned {@code Event} with provided data */ public Event cloneWithEventData(final Map<String, Object> newData) { Event newEvent = new Event.Builder(this.name, this.type, this.source, this.mask) .setEventData(newData) .build(); newEvent.uniqueIdentifier = this.uniqueIdentifier; newEvent.timestamp = this.timestamp; newEvent.responseID = this.responseID; return newEvent; } /** * Returns the {@code Event} name * * @return {@code String} representing the {@link Event} name */ public String getName() { return name; } /** * Returns the {@code Event} uniqueIdentifier * * @return {@code String} representing the {@link Event} uniqueIdentifier */ public String getUniqueIdentifier() { return uniqueIdentifier; } /** * Returns the {@code Event} source value * * @return {@code String} representing the {@link Event} source */ public String getSource() { return source; } /** * Returns the {@code Event} type value * * @return {@code String} representing the {@link Event} type */ public String getType() { return type; } /** * Retrieves the event data for current {@code Event} * * @return {@code Map<String, Object>} with the {@link Event} data key-value pairs. Returns null * if the data is null or if an error occurred while processing */ public Map<String, Object> getEventData() { return data; } /** * @return {@link Event} timestamp in milliseconds */ public long getTimestamp() { return timestamp; } /** * Pair ID for events dispatched by the receiver(s) in response to this event * * @return String response pair ID */ public String getResponseID() { return responseID; } /** * Returns the unique identifier of the parent of this event. * * @return the unique identifier of the parent of this event */ public String getParentID() { return parentID; } /** * @return event timestamp in seconds */ public long getTimestampInSeconds() { return TimeUnit.MILLISECONDS.toSeconds(timestamp); } /** * @return {@code String[]} containing properties in the Event and its data that should be used * in the hash for EventHistory storage. */ public String[] getMask() { return mask; } @NonNull @Override public String toString() { final String NEWLINE = "\n"; final String COMMA = ","; final StringBuilder sb = new StringBuilder(); sb.append("{").append(NEWLINE); sb.append(" class: Event").append(COMMA).append(NEWLINE); sb.append(" name: ").append(name).append(COMMA).append(NEWLINE); sb.append(" uniqueIdentifier: ").append(uniqueIdentifier).append(COMMA).append(NEWLINE); sb.append(" source: ").append(source).append(COMMA).append(NEWLINE); sb.append(" type: ").append(type).append(COMMA).append(NEWLINE); sb.append(" responseId: ").append(responseID).append(COMMA).append(NEWLINE); sb.append(" parentId: ").append(parentID).append(COMMA).append(NEWLINE); sb.append(" timestamp: ").append(timestamp).append(COMMA).append(NEWLINE); String dataAsStr = data == null ? "{}" : MapExtensionsKt.prettify(data); sb.append(" data: ").append(dataAsStr).append(COMMA).append(NEWLINE); sb.append(" mask: ").append(Arrays.toString(mask)).append(COMMA).append(NEWLINE); sb.append("}"); return sb.toString(); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/WrapperType.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import com.adobe.marketing.mobile.internal.CoreConstants; public enum WrapperType { NONE(CoreConstants.Wrapper.Type.NONE), REACT_NATIVE(CoreConstants.Wrapper.Type.REACT_NATIVE), FLUTTER(CoreConstants.Wrapper.Type.FLUTTER), CORDOVA(CoreConstants.Wrapper.Type.CORDOVA), UNITY(CoreConstants.Wrapper.Type.UNITY), XAMARIN(CoreConstants.Wrapper.Type.XAMARIN); private final String wrapperTag; WrapperType(final String wrapperTag) { this.wrapperTag = wrapperTag; } public String getWrapperTag() { return this.wrapperTag; } public static WrapperType fromString(final String wrapperTag) { if (CoreConstants.Wrapper.Type.REACT_NATIVE.equals(wrapperTag)) { return REACT_NATIVE; } else if (CoreConstants.Wrapper.Type.FLUTTER.equals(wrapperTag)) { return FLUTTER; } else if (CoreConstants.Wrapper.Type.CORDOVA.equals(wrapperTag)) { return CORDOVA; } else if (CoreConstants.Wrapper.Type.UNITY.equals(wrapperTag)) { return UNITY; } else if (CoreConstants.Wrapper.Type.XAMARIN.equals(wrapperTag)) { return XAMARIN; } return NONE; } public String getFriendlyName() { switch (this) { case REACT_NATIVE: return CoreConstants.Wrapper.Name.REACT_NATIVE; case FLUTTER: return CoreConstants.Wrapper.Name.FLUTTER; case CORDOVA: return CoreConstants.Wrapper.Name.CORDOVA; case UNITY: return CoreConstants.Wrapper.Name.UNITY; case XAMARIN: return CoreConstants.Wrapper.Name.XAMARIN; case NONE: default: return CoreConstants.Wrapper.Name.NONE; } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/SharedStateStatus.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; /** Type representing the state of an extension's `SharedState` */ public enum SharedStateStatus { SET, PENDING, NONE, }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/VisitorID.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import com.adobe.marketing.mobile.internal.CoreConstants; import com.adobe.marketing.mobile.services.Log; import com.adobe.marketing.mobile.util.StringUtils; /** An identifier to be used with the Adobe Experience Cloud Visitor ID Service */ public class VisitorID { private static final int RANDOM_HASH_BASE = 17; private static final int RANDOM_HASH_PADDING = 31; private final AuthenticationState authenticationState; private final String id; private final String idOrigin; private final String idType; /** * {@link AuthenticationState} for this {@link VisitorID} * * @return The {@link AuthenticationState} */ public AuthenticationState getAuthenticationState() { return authenticationState; } /** * ID for this {@link VisitorID} * * @return The {@link VisitorID} ID */ public final String getId() { return id; } /** * ID Origin for this {@link VisitorID} * * @return {@link VisitorID} Origin string */ public final String getIdOrigin() { return idOrigin; } /** * ID Type for this {@link VisitorID} * * @return {@link VisitorID} type */ public final String getIdType() { return idType; } /** Used to indicate the authentication state for the current {@link VisitorID} */ public enum AuthenticationState { UNKNOWN(0), AUTHENTICATED(1), LOGGED_OUT(2); private final int value; AuthenticationState(final int value) { this.value = value; } public int getValue() { return value; } public static AuthenticationState fromInteger(final int authStateInteger) { for (AuthenticationState b : AuthenticationState.values()) { if (b.getValue() == authStateInteger) { return b; } } return AuthenticationState.UNKNOWN; } } /** * Constructor initializes {@link #id}, {@link #idOrigin}, {@link #idType} and {@link * #authenticationState}. * * @param idOrigin {@link String} containing the ID Origin for the {@link VisitorID} * @param idType {@code String} containing the ID Type for the {@code VisitorID}; it should not * be null/empty * @param id {@code String} containing the ID for the {@code VisitorID}; it should not be * null/empty * @param authenticationState {@link AuthenticationState} containing the authentication state * for the {@code VisitorID} * @throws IllegalStateException if the provided {@code idType} is null or empty */ public VisitorID( final String idOrigin, final String idType, final String id, final AuthenticationState authenticationState) { // TODO: cleanContextDataKey logic will be moved to Analytics extension // https://github.com/adobe/aepsdk-core-android/issues/217 // final String cleanIdType = ContextDataUtil.cleanContextDataKey(idType); // idType cannot be null/empty if (StringUtils.isNullOrEmpty(idType)) { throw new IllegalStateException("idType parameter cannot be null or empty"); } // id cannot be null/empty // Do not throw IllegalStateException to maintain backwards compatibility if (StringUtils.isNullOrEmpty(id)) { Log.debug( CoreConstants.LOG_TAG, "VisitorID", "The custom VisitorID should not have null/empty id, this VisitorID will be" + " ignored"); } this.idOrigin = idOrigin; this.idType = idType; this.id = id; this.authenticationState = authenticationState; } /** * Compares the provided {@link VisitorID} object with this and determines if they are equal. * * <p>The comparison checks that the provided {@link Object} parameter is a {@code VisitorID} * instance. If it is, then checks the equality of the {@link #idType} and {@link #id} fields * between the two objects. * * @param o {@code VisitorID} object to compare against * @return {@code boolean} indicating whether the provided {@code VisitorID} object is equal to * this */ @Override public boolean equals(final Object o) { if (o == this) { return true; } if (!(o instanceof VisitorID)) { return false; } VisitorID idToCompare = (VisitorID) o; if (!this.idType.equals(idToCompare.idType)) { return false; } // if id is null, the passed in ID must be null to match if (this.id == null) { return idToCompare.id == null; } if (idToCompare.id == null) { return false; } return this.id.compareTo(idToCompare.id) == 0; } @Override public int hashCode() { int result = RANDOM_HASH_BASE; result = RANDOM_HASH_PADDING * result + id.hashCode(); result = RANDOM_HASH_PADDING * result + idType.hashCode(); return result; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/AdobeCallbackWithError.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; @SuppressWarnings("unused") public interface AdobeCallbackWithError<T> extends AdobeCallback<T> { void fail(final AdobeError error); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/BroadcastHandler.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import android.content.Context; import android.content.Intent; interface BroadcastHandler { /** * Handle the Android system broadcast. This may marshall the data from the Intent, and convert * it into an event data {@code Map<String, Object>} and call the corresponding API to dispatch * the data in an {@link Event}. * * @param context Context as received from the Android Broadcast receiver. * @param intent Intent as received from the Android Broadcast receiver. */ void handleBroadcast(Context context, Intent intent); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/EventType.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; /** * Class to define the type of an {@code Event} * * @author Adobe Systems Incorporated * @version 5.0 * @see Event * @see EventSource */ public final class EventType { private EventType() {} public static final String ACQUISITION = "com.adobe.eventType.acquisition"; public static final String ANALYTICS = "com.adobe.eventType.analytics"; public static final String ASSURANCE = "com.adobe.eventType.assurance"; public static final String AUDIENCEMANAGER = "com.adobe.eventType.audienceManager"; public static final String CAMPAIGN = "com.adobe.eventType.campaign"; public static final String CONFIGURATION = "com.adobe.eventType.configuration"; public static final String CONSENT = "com.adobe.eventType.edgeConsent"; public static final String CUSTOM = "com.adobe.eventType.custom"; public static final String EDGE = "com.adobe.eventType.edge"; public static final String EDGE_IDENTITY = "com.adobe.eventType.edgeIdentity"; public static final String EDGE_MEDIA = "com.adobe.eventType.edgeMedia"; public static final String GENERIC_DATA = "com.adobe.eventType.generic.data"; public static final String GENERIC_IDENTITY = "com.adobe.eventType.generic.identity"; public static final String GENERIC_LIFECYCLE = "com.adobe.eventType.generic.lifecycle"; public static final String GENERIC_PII = "com.adobe.eventType.generic.pii"; public static final String GENERIC_TRACK = "com.adobe.eventType.generic.track"; public static final String HUB = "com.adobe.eventType.hub"; public static final String IDENTITY = "com.adobe.eventType.identity"; public static final String LIFECYCLE = "com.adobe.eventType.lifecycle"; public static final String LOCATION = "com.adobe.eventType.location"; public static final String MEDIA = "com.adobe.eventType.media"; public static final String MESSAGING = "com.adobe.eventType.messaging"; public static final String PII = "com.adobe.eventType.pii"; public static final String PLACES = "com.adobe.eventType.places"; public static final String RULES_ENGINE = "com.adobe.eventType.rulesEngine"; public static final String SIGNAL = "com.adobe.eventType.signal"; public static final String SYSTEM = "com.adobe.eventType.system"; public static final String TARGET = "com.adobe.eventType.target"; public static final String USERPROFILE = "com.adobe.eventType.userProfile"; public static final String WILDCARD = "com.adobe.eventType._wildcard_"; }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/EventSource.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; /** * Class to define the source of an {@code Event} * * @author Adobe Systems Incorporated * @version 5.0 * @see Event * @see EventType */ public final class EventSource { private EventSource() {} public static final String NONE = "com.adobe.eventSource.none"; public static final String OS = "com.adobe.eventSource.os"; public static final String REQUEST_CONTENT = "com.adobe.eventSource.requestContent"; public static final String REQUEST_IDENTITY = "com.adobe.eventSource.requestIdentity"; public static final String REQUEST_PROFILE = "com.adobe.eventSource.requestProfile"; public static final String REQUEST_RESET = "com.adobe.eventSource.requestReset"; public static final String RESPONSE_CONTENT = "com.adobe.eventSource.responseContent"; public static final String RESPONSE_IDENTITY = "com.adobe.eventSource.responseIdentity"; public static final String RESPONSE_PROFILE = "com.adobe.eventSource.responseProfile"; public static final String SHARED_STATE = "com.adobe.eventSource.sharedState"; public static final String WILDCARD = "com.adobe.eventSource._wildcard_"; public static final String APPLICATION_LAUNCH = "com.adobe.eventSource.applicationLaunch"; public static final String APPLICATION_CLOSE = "com.adobe.eventSource.applicationClose"; public static final String CONSENT_PREFERENCE = "consent:preferences"; public static final String UPDATE_CONSENT = "com.adobe.eventSource.updateConsent"; public static final String RESET_COMPLETE = "com.adobe.eventSource.resetComplete"; public static final String UPDATE_IDENTITY = "com.adobe.eventSource.updateIdentity"; public static final String REMOVE_IDENTITY = "com.adobe.eventSource.removeIdentity"; public static final String ERROR_RESPONSE_CONTENT = "com.adobe.eventSource.errorResponseContent"; public static final String CREATE_TRACKER = "com.adobe.eventSource.createTracker"; public static final String TRACK_MEDIA = "com.adobe.eventSource.trackMedia"; public static final String CONTENT_COMPLETE = "com.adobe.eventSource.contentComplete"; public static final String DEBUG = "com.adobe.eventSource.debug"; }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/AdobeCallback.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; @SuppressWarnings("unused") public interface AdobeCallback<T> { void call(final T value); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/AdobeError.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import java.io.Serializable; /** */ public class AdobeError implements Serializable { private static final long serialVersionUID = 1L; /** when something unexpected happens internally. */ public static final AdobeError UNEXPECTED_ERROR = new AdobeError("general.unexpected", 0); /** when a timeout happens. */ public static final AdobeError CALLBACK_TIMEOUT = new AdobeError("general.callback.timeout", 1); /** when a callback is null. */ public static final AdobeError CALLBACK_NULL = new AdobeError("general.callback.null", 2); /** when a server error happens. */ public static final AdobeError SERVER_ERROR = new AdobeError("general.server.error", 4); /** when a network error happens. */ public static final AdobeError NETWORK_ERROR = new AdobeError("general.network.error", 5); /** when an invalid request is made. */ public static final AdobeError INVALID_REQUEST = new AdobeError("general.request.invalid", 6); /** when an invalid response is received. */ public static final AdobeError INVALID_RESPONSE = new AdobeError("general.response.invalid", 7); /** when a extension is not initialized. */ public static final AdobeError EXTENSION_NOT_INITIALIZED = new AdobeError("general.extension.not.initialized", 11); private final String errorName; private final int errorCode; protected AdobeError(final String errorName, final int errorCode) { this.errorName = errorName; this.errorCode = errorCode; } /** * Retrieves current error's name as a {@code String}. * * @return the error name {@link String} */ public String getErrorName() { return errorName; } /** * Retrieves current error's code as a {@code int}. * * @return the error code {@code int} */ public int getErrorCode() { return errorCode; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/ExtensionHelper.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.Map; /** Helper methods to access protected Extension methods from different packages */ public class ExtensionHelper { private ExtensionHelper() {} public static @Nullable String getName(@NonNull final Extension extension) { try { return extension.getName(); } catch (Exception e) { return null; } } public static @Nullable String getFriendlyName(@NonNull final Extension extension) { try { return extension.getFriendlyName(); } catch (Exception e) { return null; } } public static @Nullable String getVersion(@NonNull final Extension extension) { try { return extension.getVersion(); } catch (Exception e) { return null; } } public static @Nullable Map<String, String> getMetadata(@NonNull final Extension extension) { try { return extension.getMetadata(); } catch (Exception e) { return null; } } public static void notifyUnregistered(@NonNull final Extension extension) { try { extension.onUnregistered(); } catch (Exception ignored) { } } public static void notifyRegistered(@NonNull final Extension extension) { try { extension.onRegistered(); } catch (Exception ignored) { } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/Evaluable.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; /** * Evaluable Interface. * * <p>The classes that implements {@link Evaluable} are {@link ComparisonExpression} {@link * LogicalExpression} {@link UnaryExpression} */ public interface Evaluable { RulesResult evaluate(final Context context); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/RulesEngine.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; import java.util.ArrayList; import java.util.List; /** RulesEngine to evaluate matching rules for given input data */ public class RulesEngine<T extends Rule> { private final Object rulesEngineMutex = new Object(); private final Evaluating evaluator; private final Transforming transformer; private List<T> rules; public RulesEngine(final Evaluating evaluator, final Transforming transformer) { this.evaluator = evaluator; this.transformer = transformer; this.rules = new ArrayList<>(); } public List<T> evaluate(final TokenFinder tokenFinder) { synchronized (rulesEngineMutex) { final Context context = new Context(tokenFinder, evaluator, transformer); List<T> triggerRules = new ArrayList<>(); for (final T rule : rules) { RulesResult result = rule.getEvaluable().evaluate(context); if (result.isSuccess()) { triggerRules.add(rule); } } return triggerRules; } } public void replaceRules(final List<T> newRules) { if (newRules == null) { return; } synchronized (rulesEngineMutex) { rules = new ArrayList<>(newRules); } } public void addRules(final List<T> newRules) { synchronized (rulesEngineMutex) { rules.addAll(newRules); } } public List<T> getRules() { return new ArrayList<>(rules); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/TokenFinder.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; public interface TokenFinder { Object get(final String key); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/TransformerBlock.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; @FunctionalInterface public interface TransformerBlock<T> { T transform(final Object e); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/Segment.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; /** * A segment represents a part of text that can be evaluated to a value. There are two types of * Segment - {@link SegmentToken} - {@link SegmentText} * * <p>The following string is parsed by {@link TemplateParser} to have 3 segments. "Hi {{username}}, * Welcome to New York" 1. Hi --> (SegmentText) 2. {{username}} --> (SegmentToken) 3. , Welcome to * New York --> (Segment Text) */ interface Segment { String getContent(final TokenFinder tokenFinder, final Transforming transformers); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/SegmentText.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; /** SegmentText represents plain text. */ public class SegmentText implements Segment { private final String content; public SegmentText(final String content) { this.content = content; } @Override public String getContent(final TokenFinder tokenFinder, final Transforming transformer) { return content; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/Transformer.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; import java.util.HashMap; import java.util.Map; public class Transformer implements Transforming { Map<String, TransformerBlock<?>> transformations = new HashMap<>(); public void register(final String name, final TransformerBlock<?> transformerBlock) { transformations.put(name, transformerBlock); } @Override public Object transform(final String name, final Object parameter) { TransformerBlock<?> block = transformations.get(name); if (block == null) { return parameter; } return block.transform(parameter); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/Operand.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; /** * Interface for Operands. * * <p>The classes that implements {@link Operand} are {@link OperandLiteral} {@link * OperandMustacheToken} {@link OperandFunction} */ public interface Operand<T> { /** * All operand's must implement this to retrieve its resolved value. * * @param context The context contains details for token swapping and transforming the operand * if required. * @return the resolved operand value */ T resolve(final Context context); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/Context.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; public class Context { public final TokenFinder tokenFinder; public final Evaluating evaluator; public final Transforming transformer; public Context( final TokenFinder tokenFinder, final Evaluating evaluator, final Transforming transformer) { this.tokenFinder = tokenFinder; this.evaluator = evaluator; this.transformer = transformer; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/RulesResult.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; public class RulesResult { public enum FailureType { UNKNOWN, CONDITION_FAILED, TYPE_MISMATCHED, MISSING_OPERATOR, INVALID_OPERAND, } private final boolean isSuccess; private final String failureMessage; private final FailureType failureType; public static final RulesResult SUCCESS = new RulesResult(true); public RulesResult(final FailureType failureType, final String failureMessage) { this.isSuccess = false; this.failureMessage = failureMessage; this.failureType = failureType; } public boolean isSuccess() { return isSuccess; } public String getFailureMessage() { return failureMessage; } public FailureType getFailureType() { return failureType; } private RulesResult(final boolean isSuccess) { this.isSuccess = isSuccess; this.failureMessage = null; this.failureType = null; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/OperandLiteral.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; public class OperandLiteral<T> implements Operand<T> { private final T value; public OperandLiteral(final T value) { this.value = value; } @Override public T resolve(final Context context) { return this.value; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/UnaryExpression.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; public class UnaryExpression<A> implements Evaluable { private final Operand<A> lhs; private final String operationName; public UnaryExpression(final Operand<A> lhs, final String operationName) { this.lhs = lhs; this.operationName = operationName; } @Override public RulesResult evaluate(final Context context) { A resolvedLhs = null; if (lhs != null) { resolvedLhs = lhs.resolve(context); } if (operationName == null || operationName.isEmpty()) { return new RulesResult( RulesResult.FailureType.INVALID_OPERAND, String.format("Evaluating %s %s returned false", resolvedLhs, operationName)); } return context.evaluator.evaluate(operationName, resolvedLhs); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/LogicalExpression.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; import java.util.List; public class LogicalExpression implements Evaluable { public final List<Evaluable> operands; public final String operationName; public LogicalExpression(final List<Evaluable> operands, final String operationName) { this.operands = operands; this.operationName = operationName; } @Override public RulesResult evaluate(final Context context) { if (operationName == null || operationName.isEmpty()) { return new RulesResult( RulesResult.FailureType.MISSING_OPERATOR, "Null or empty operator for logical expression"); } switch (operationName) { case "and": return performAndOperation(context, operands); case "or": return performOrOperation(context, operands); default: return new RulesResult( RulesResult.FailureType.MISSING_OPERATOR, String.format("Unknown conjunction operator - %s.", operationName)); } } private RulesResult performAndOperation( final Context context, final List<Evaluable> resolvedOperands) { for (Evaluable evaluable : resolvedOperands) { if (evaluable != null) { RulesResult rulesResult = evaluable.evaluate(context); if (!rulesResult.isSuccess()) { return new RulesResult( RulesResult.FailureType.CONDITION_FAILED, "AND operation returned false."); } } } return RulesResult.SUCCESS; } private RulesResult performOrOperation( final Context context, final List<Evaluable> resolvedOperands) { for (Evaluable evaluable : resolvedOperands) { if (evaluable != null) { RulesResult rulesResult = evaluable.evaluate(context); if (rulesResult.isSuccess()) { return RulesResult.SUCCESS; } } } return new RulesResult( RulesResult.FailureType.CONDITION_FAILED, "OR operation returned false."); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/FunctionBlock.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; @FunctionalInterface public interface FunctionBlock<T> { T execute(final Object... e); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/ComparisonExpression.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; /** * {@link ComparisonExpression} allows for comparison of two operands and evaluates to a True or * False. Comparison operators include LessThan, LessThanOrEqual to, Equal, NotEqual, GreaterThan, * GreaterThanOrEqual to, Contains and notContains. */ public class ComparisonExpression<A, B> implements Evaluable { private final Operand<A> lhs; private final Operand<B> rhs; private final String operationName; /** * Initializer. Constructs the {@link ComparisonExpression} object with operands and operation * name. * * @param lhs an {@link Operand} * @param operationName A {@code String} value defining the operation. * @param rhs an {@link Operand} */ public ComparisonExpression( final Operand<A> lhs, final String operationName, final Operand<B> rhs) { this.lhs = lhs; this.operationName = operationName; this.rhs = rhs; } /** * Call this method to evaluate this {@link ComparisonExpression}. * * <p>This method always returns a valid non null {@link RulesResult} object. Returns * RulesResult failure if the operation name or either of the operands are null. * * @param context The context containing details for token swapping and transforming the operand * if required. A non null value of {@link Context} is expected to be passed to this method. * @return A {@link RulesResult} object representing a evaluated rule */ public RulesResult evaluate(final Context context) { if (operationName == null) { return new RulesResult( RulesResult.FailureType.MISSING_OPERATOR, "Operator is null, Comparison returned false"); } if (lhs == null || rhs == null) { return new RulesResult( RulesResult.FailureType.INVALID_OPERAND, "Operand is null, Comparison returned false."); } A resolvedLhs = lhs.resolve(context); B resolvedRhs = rhs.resolve(context); if (resolvedLhs == null || resolvedRhs == null) { return new RulesResult( RulesResult.FailureType.INVALID_OPERAND, String.format( "Comparison %s %s %s returned false", resolvedLhs, operationName, resolvedRhs)); } return context.evaluator.evaluate(resolvedLhs, operationName, resolvedRhs); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/OperandFunction.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; public class OperandFunction<T> implements Operand<T> { private final FunctionBlock<T> block; private final Object[] functionParameters; public OperandFunction(final FunctionBlock<T> block, final Object... functionParameters) { this.block = block; this.functionParameters = functionParameters; } @Override public T resolve(final Context context) { return block.execute(functionParameters); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/Transforming.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; public interface Transforming { Object transform(final String name, final Object parameter); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/TemplateParser.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; import java.util.ArrayList; import java.util.List; public class TemplateParser { private static final DelimiterPair defaultDelimiter = new DelimiterPair("{{", "}}"); static List<Segment> parse(final String templateString) { return TemplateParser.parse(templateString, defaultDelimiter); } static List<Segment> parse(final String templateString, final DelimiterPair delimiter) { List<Segment> tokens = new ArrayList<>(); if (templateString == null || templateString.isEmpty()) { return tokens; } DelimiterPair currentDelimiter = delimiter == null ? defaultDelimiter : delimiter; int i = 0; int end = templateString.length(); Parser parser = new Parser(i, State.START); while (i < end) { switch (parser.state) { case START: if (templateString.substring(i).startsWith(currentDelimiter.getStartTag())) { parser.setState(i, State.TAG); i = templateString.indexOf(currentDelimiter.getStartTag(), i) + 1; } else { parser.setState(i, State.TEXT); } break; case TEXT: if (templateString.substring(i).startsWith(currentDelimiter.getStartTag())) { if (parser.index != i) { tokens.add(new SegmentText(templateString.substring(parser.index, i))); } parser.setState(i, State.TAG); i = templateString.indexOf(currentDelimiter.getStartTag(), i) + 1; } break; case TAG: if (templateString.substring(i).startsWith(currentDelimiter.getEndTag())) { int tokenContentStartIndex = parser.index + currentDelimiter.getStartLength(); tokens.add( new SegmentToken( templateString.substring(tokenContentStartIndex, i))); parser.state = State.START; i = templateString.indexOf(currentDelimiter.getEndTag(), i) + 1; } break; } i++; } switch (parser.state) { case START: break; case TEXT: tokens.add(new SegmentText(templateString.substring(parser.index, i))); break; case TAG: return new ArrayList<>(); } return tokens; } } class Parser { int index; State state; Parser(final int index, final State state) { this.index = index; this.state = state; } public void setState(final int index, final State state) { this.state = state; this.index = index; } } enum State { START, TEXT, TAG, }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/OperandMustacheToken.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; import java.util.List; /** Class to handle the mustache token Operand. */ public class OperandMustacheToken<T> implements Operand<T> { private static final String LOG_TAG = "OperandMustacheToken"; private final MustacheToken mustacheToken; private final Class<T> tClass; /** * Constructor. Initialize this operand using a tokenString. A valid tokenString has only one * token. For example : {{region.city}} * {%~state.com.adobe.marketing,mobile.lifecycle.contextdata.deviceName%} * * <p>Following are considered are invalid token strings 1. region.city - (this string does not * contain token delimiters) 2. {{region.city - (this string is not enclosed between delimiters) * 3. some{{region.city}} - (this string does not start with a valid token) * * @param tokenString string representing a mustache token operand * @param tClass string representing a mustache token operand */ public OperandMustacheToken(final String tokenString, final Class<T> tClass) { MustacheToken mustacheToken = null; // Mustache token operands must have only one token, ignore others. final List<Segment> segmentList = TemplateParser.parse(tokenString); if (segmentList.size() > 0 && segmentList.get(0) instanceof SegmentToken) { SegmentToken segmentToken = (SegmentToken) segmentList.get(0); mustacheToken = segmentToken.getMustacheToken(); } this.mustacheToken = mustacheToken; this.tClass = tClass; } /** * Returns the resolved value of the MustacheToken operand. An invalid mustacheToken operand * returns null. * * @param context The context contains details for token swapping and transforming the operand * if required * @return the resolved operand value */ @Override public T resolve(final Context context) { if (mustacheToken == null) { return null; } Object resolvedValue = mustacheToken.resolve(context.tokenFinder, context.transformer); try { return tClass.cast(resolvedValue); } catch (ClassCastException ex) { return null; } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/Template.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; import java.util.List; public class Template { private final List<Segment> segments; public Template(final String templateString) { this.segments = TemplateParser.parse(templateString); } public Template(final String templateString, final DelimiterPair delimiterPair) { this.segments = TemplateParser.parse(templateString, delimiterPair); } public String render(final TokenFinder tokenFinder, final Transforming transformer) { StringBuilder stringBuilder = new StringBuilder(); for (Segment eachSegment : segments) { stringBuilder.append(eachSegment.getContent(tokenFinder, transformer)); } return stringBuilder.toString(); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/DelimiterPair.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; /** * Class representing delimiter pair for tokens. * * <p>The default delimiter pair from launch rules are "{%" "%}" eg token: {%region.cityName%} */ public class DelimiterPair { private final String startTag; private final String endTag; /** * Constructor. * * @param startString the startTag for this {@link DelimiterPair} * @param endString the endTag for this {@link DelimiterPair} */ public DelimiterPair(final String startString, final String endString) { this.startTag = startString; this.endTag = endString; } /** * @return the startTag for this {@link DelimiterPair} */ String getStartTag() { return startTag; } /** * @return the endTag for this {@link DelimiterPair} */ String getEndTag() { return endTag; } /** * @return the character length of startTag of this delimiter */ int getStartLength() { return startTag.length(); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/SegmentToken.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; /** * SegmentToken represents token, whose value is substituted by the {@link TokenFinder} or {@link * Transforming}. */ public class SegmentToken implements Segment { private final MustacheToken mustacheToken; public SegmentToken(final String mustacheString) { this.mustacheToken = new MustacheToken(mustacheString); } public MustacheToken getMustacheToken() { return mustacheToken; } /** Retrieves the evaluated value of this {@link SegmentToken} */ @Override public String getContent(final TokenFinder tokenFinder, final Transforming transformer) { Object resolvedToken = mustacheToken.resolve(tokenFinder, transformer); if (resolvedToken != null) { return resolvedToken.toString(); } return ""; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/ConditionEvaluator.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; import java.util.regex.Pattern; public class ConditionEvaluator implements Evaluating { private final Option option; private static final String OPERATOR_EQUALS = "equals"; private static final String OPERATOR_NOT_EQUALS = "notEquals"; private static final String OPERATOR_GREATER_THAN = "greaterThan"; private static final String OPERATOR_GREATER_THAN_OR_EQUALS = "greaterEqual"; private static final String OPERATOR_LESS_THAN = "lessThan"; private static final String OPERATOR_LESS_THAN_OR_EQUALS = "lessEqual"; private static final String OPERATOR_CONTAINS = "contains"; private static final String OPERATOR_NOT_CONTAINS = "notContains"; private static final String OPERATOR_STARTS_WITH = "startsWith"; private static final String OPERATOR_ENDS_WITH = "endsWith"; private static final String OPERATOR_EXISTS = "exists"; private static final String OPERATOR_NOT_EXISTS = "notExist"; public enum Option { DEFAULT, // For case sensitive string operations CASE_INSENSITIVE, // For case insensitive string operations } public ConditionEvaluator(final Option option) { this.option = option; } public ConditionEvaluator() { this.option = Option.DEFAULT; } /** * Runs operation on the operands. * * <p>This method always returns a valid non null {@link RulesResult} object. {@link * RulesResult#SUCCESS} is returned if the operation on the operands evaluates to true. * * @param lhs A resolved {@link Operand} * @param operation A {@link String} representing the operation to be performed on the operands * @param rhs A resolved {@code Operand} */ @Override public <A, B> RulesResult evaluate(final A lhs, final String operation, final B rhs) { boolean evaluationResult; switch (operation) { case OPERATOR_EQUALS: evaluationResult = this.checkEqual(lhs, rhs); break; case OPERATOR_NOT_EQUALS: evaluationResult = this.notEqual(lhs, rhs); break; case OPERATOR_STARTS_WITH: evaluationResult = this.startsWith(lhs, rhs); break; case OPERATOR_ENDS_WITH: evaluationResult = this.endsWith(lhs, rhs); break; case OPERATOR_GREATER_THAN: evaluationResult = this.greaterThan(lhs, rhs); break; case OPERATOR_GREATER_THAN_OR_EQUALS: evaluationResult = this.greaterThanEquals(lhs, rhs); break; case OPERATOR_LESS_THAN: evaluationResult = this.lesserThan(lhs, rhs); break; case OPERATOR_LESS_THAN_OR_EQUALS: evaluationResult = this.lesserThanOrEqual(lhs, rhs); break; case OPERATOR_CONTAINS: evaluationResult = this.contains(lhs, rhs); break; case OPERATOR_NOT_CONTAINS: evaluationResult = this.notContains(lhs, rhs); break; default: return new RulesResult( RulesResult.FailureType.MISSING_OPERATOR, String.format("Operator is invalid \"%s\"", operation)); } return evaluationResult ? RulesResult.SUCCESS : new RulesResult( RulesResult.FailureType.CONDITION_FAILED, String.format("Condition not matched for operation \"%s\"", operation)); } @Override public <A> RulesResult evaluate(final String operation, final A lhs) { boolean evaluationResult; switch (operation) { case OPERATOR_EXISTS: evaluationResult = this.exists(lhs); break; case OPERATOR_NOT_EXISTS: evaluationResult = this.notExists(lhs); break; default: return new RulesResult( RulesResult.FailureType.MISSING_OPERATOR, String.format("Operator is invalid \"%s\"", operation)); } return evaluationResult ? RulesResult.SUCCESS : new RulesResult( RulesResult.FailureType.CONDITION_FAILED, String.format("Condition not matched for operation \"%s\"", operation)); } // -------------------------------------------------------------------------- // Private - Operator definitions // -------------------------------------------------------------------------- private boolean checkEqual(final Object lhs, final Object rhs) { if (lhs instanceof String && rhs instanceof String && option == Option.CASE_INSENSITIVE) { String lhsValue = lhs.toString(); String rhsValue = rhs.toString(); return lhsValue.equalsIgnoreCase(rhsValue); } return lhs.equals(rhs); } private boolean notEqual(final Object lhs, final Object rhs) { return !checkEqual(lhs, rhs); } private boolean startsWith(final Object lhs, final Object rhs) { if (lhs instanceof String && rhs instanceof String) { String lhsValue = lhs.toString(); String rhsValue = rhs.toString(); String matcherMode = option == ConditionEvaluator.Option.CASE_INSENSITIVE ? "(?i)" : ""; return lhsValue.matches(matcherMode + Pattern.quote(rhsValue) + ".*"); } return false; } private boolean endsWith(final Object lhs, final Object rhs) { if (lhs instanceof String && rhs instanceof String) { String lhsValue = lhs.toString(); String rhsValue = rhs.toString(); String matcherMode = option == ConditionEvaluator.Option.CASE_INSENSITIVE ? "(?i)" : ""; return lhsValue.matches(matcherMode + ".*" + Pattern.quote(rhsValue)); } return false; } private boolean exists(final Object lhs) { return lhs != null; } private boolean notExists(final Object lhs) { return lhs == null; } // -------------------------------------------------------------------------- // Private - Operator definitions coming soon // -------------------------------------------------------------------------- private boolean greaterThan(final Object lhs, final Object rhs) { Double resolvedLhs = tryParseDouble(lhs); Double resolvedRhs = tryParseDouble(rhs); if (resolvedLhs == null || resolvedRhs == null) { return false; } return resolvedLhs > resolvedRhs; } private boolean greaterThanEquals(final Object lhs, final Object rhs) { Double resolvedLhs = tryParseDouble(lhs); Double resolvedRhs = tryParseDouble(rhs); if (resolvedLhs == null || resolvedRhs == null) { return false; } return resolvedLhs >= resolvedRhs; } private boolean lesserThan(final Object lhs, final Object rhs) { Double resolvedLhs = tryParseDouble(lhs); Double resolvedRhs = tryParseDouble(rhs); if (resolvedLhs == null || resolvedRhs == null) { return false; } return resolvedLhs < resolvedRhs; } private boolean lesserThanOrEqual(final Object lhs, final Object rhs) { Double resolvedLhs = tryParseDouble(lhs); Double resolvedRhs = tryParseDouble(rhs); if (resolvedLhs == null || resolvedRhs == null) { return false; } return resolvedLhs <= resolvedRhs; } private boolean contains(final Object lhs, final Object rhs) { if (lhs instanceof String && rhs instanceof String) { String lhsValue = lhs.toString(); String rhsValue = rhs.toString(); if (option == ConditionEvaluator.Option.CASE_INSENSITIVE) { lhsValue = lhsValue.toLowerCase(); rhsValue = rhsValue.toLowerCase(); } return lhsValue.contains(rhsValue); } return false; } private boolean notContains(final Object lhs, final Object rhs) { return !contains(lhs, rhs); } private Double tryParseDouble(final Object value) { try { return Double.valueOf(value.toString()); } catch (Exception ex) { return null; } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/MustacheToken.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class representing mustache token. * * <p>Once a token is identified in any part of the rule, use this class to obtain the resolved * value of the token. A token can be of two types 1. Variable Following example demonstrates * variable token to retrieve the "city" details from the SDK context. {{region.city}} 2. Function * Following example demonstrates function token to urlEncode the provided webURL. * {{urlenc(http://adobe.com)}} */ class MustacheToken { private final Type tokenType; private final String tokenString; private String functionName; private MustacheToken innerVariable; /** * Constructor to initialize the mustache token. * * <p>This constructor automatically recognizes the token type from the provided token string * * @param tokenString the token string without the delimiters representing the token */ MustacheToken(final String tokenString) { Matcher functionMatcher = Pattern.compile("\\(([^)]+)\\)").matcher(tokenString); this.tokenString = tokenString; // check if the token is a function if (functionMatcher.find()) { innerVariable = new MustacheToken(functionMatcher.group(1)); functionName = tokenString.substring(0, functionMatcher.start()); tokenType = Type.FUNCTION; return; } tokenType = Type.VARIABLE; } /** * Resolves the token into its corresponding value. * * @param tokenFinder A {@link TokenFinder} instance that contains SDK context to replace tokens * @param transformers A set of transformers to evaluate the function tokens. * @return value of resolved token. */ protected Object resolve(final TokenFinder tokenFinder, final Transforming transformers) { if (tokenType == Type.FUNCTION) { return transformers.transform( this.functionName, innerVariable.resolve(tokenFinder, transformers)); } else { return tokenFinder.get(tokenString); } } private enum Type { FUNCTION, VARIABLE, } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/Rule.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; /** Interface to be implemented by defining rule element. */ public interface Rule { Evaluable getEvaluable(); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/rulesengine/Evaluating.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.rulesengine; public interface Evaluating { <A, B> RulesResult evaluate(final A lhs, final String operation, final B rhs); <A> RulesResult evaluate(final String operation, final A lhs); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/StringUtils.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util; public final class StringUtils { private StringUtils() {} /** * Checks if a {@code String} is null, empty or it only contains whitespaces. * * @param str the {@link String} that we want to check * @return {@code boolean} with the evaluation result */ public static boolean isNullOrEmpty(final String str) { return str == null || str.trim().isEmpty(); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/StreamUtils.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util; import com.adobe.marketing.mobile.internal.CoreConstants; import com.adobe.marketing.mobile.services.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; public final class StreamUtils { private static final int STREAM_READ_BUFFER_SIZE = 1024; private static final String TAG = "StreamUtils"; private StreamUtils() {} /** * Reads the contents of the {@code InputStream} as a String. The input stream provided will be * closed after contents are read. * * @param inputStream {@link InputStream} to read * @return {@link String} representation of the input stream */ public static String readAsString(final InputStream inputStream) { if (inputStream == null) { return null; } try (final ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { final byte[] data = new byte[STREAM_READ_BUFFER_SIZE]; int bytesRead; while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, bytesRead); } final byte[] byteArray = buffer.toByteArray(); return new String(byteArray, StandardCharsets.UTF_8); } catch (final IOException ex) { Log.trace( CoreConstants.LOG_TAG, TAG, "Unable to convert InputStream to String," + ex.getLocalizedMessage()); return null; } finally { try { inputStream.close(); } catch (final IOException ex) { Log.trace( CoreConstants.LOG_TAG, TAG, "Unable to close InputStream," + ex.getLocalizedMessage()); } } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/CloneFailedException.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util; import androidx.annotation.NonNull; /** * Exception thrown by {@link EventDataUtils} to indicate that an exception occurred during deep * clone. */ public class CloneFailedException extends Exception { private final Reason reason; /** Enum to indicate the reason for the exception. */ enum Reason { MAX_DEPTH_REACHED, UNSUPPORTED_TYPE, UNKNOWN } /** * Constructor. * * @param message {@code String} message for the exception */ public CloneFailedException(final String message) { this(message, Reason.UNKNOWN); } /** * Constructor. * * @param reason the {@link Reason} for the exception */ CloneFailedException(@NonNull final Reason reason) { this(reason.toString(), reason); } /** * Private constructor to unify public constructors and allow cascading. * * @param message {@code String} message for the exception * @param reason the {@link Reason} for the exception */ private CloneFailedException(@NonNull final String message, @NonNull final Reason reason) { super(message); this.reason = reason; } /** * Returns the {@link Reason} for the exception. * * @return returns the {@link Reason} for the exception */ @NonNull Reason getReason() { return reason; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/DataReaderException.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util; /** Exception thrown by {@link DataReader} to indicate an error occurred reading object. */ public class DataReaderException extends Exception { /** * Constructor. * * @param message {@code String} message for the exception */ public DataReaderException(final String message) { super(message); } /** * Constructor. * * @param inner {@code Exception} that caused this exception */ public DataReaderException(final Exception inner) { super(inner); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/MapUtils.java
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util; import androidx.annotation.Nullable; import java.util.Collection; import java.util.Map; /** Utility class for Maps */ public final class MapUtils { private MapUtils() {} /** * Checks if the provided {@code map} is null or it has no element * * @param map the {@code map} to be verified * @return true if null or empty, false otherwise */ public static boolean isNullOrEmpty(@Nullable final Map<?, ?> map) { return map == null || map.isEmpty(); } /** * Adds {@code key}/{@code value} to {@code map} if {@code value} is not null or an empty * string, map or collection. * * @param map collection to put {@code values} mapped to {@code key} if {@code values} is * non-null and contains at least one entry * @param key key used to map {@code value} in {@code map} * @param value an object to add to {@code map} if not null or empty */ public static void putIfNotEmpty( @Nullable final Map<String, Object> map, @Nullable final String key, @Nullable final Object value) { if (map == null || key == null || value == null) { return; } boolean isValueEmpty = false; if (value instanceof String) { isValueEmpty = ((String) value).isEmpty(); } else if (value instanceof Map<?, ?>) { isValueEmpty = ((Map<?, ?>) value).isEmpty(); } else if (value instanceof Collection<?>) { isValueEmpty = ((Collection<?>) value).isEmpty(); } if (!isValueEmpty) { map.put(key, value); } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/DataReader.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util; import java.util.List; import java.util.Map; /** * Utility to read data from {@code Event} data which is represented as {@code Map<String, Object>} * in a type safe way. * * <p>The value of an {@code Event} data key can be obtained in multiple ways: * * <ul> * <li>The {@code DataReader.optXyz(...)} methods are typically the best choice for users. These * methods return the value as an {@code xyz}. If the value is missing or is not an {@code * xyz}, the method will return a default value. Implicit conversions between types are not * performed, except between numeric types. No implicit conversions even between numeric types * are performed when reading as {@code Map} or {@code List}. * <li>The {@code DataReader.getXyz(...)} methods return the value as an {@code xyz}. If the value * is missing or is not an {@code xyz} the method will throw. Implicit conversions between * types are not performed, except between numeric types. No implicit conversions even between * numeric types are performed when reading as {@code Map} or {@code List}. * </ul> */ public class DataReader { private DataReader() {} private static boolean checkOverflow(final Class<?> clazz, final Number n) { if (Double.class.equals(clazz)) { return false; } else if (Float.class.equals(clazz)) { if (n instanceof Double) { double valAsDouble = n.doubleValue(); return valAsDouble < Float.MIN_VALUE || valAsDouble > Float.MAX_VALUE; } return false; } else if (Long.class.equals(clazz)) { if (n instanceof Double || n instanceof Float) { double valAsDouble = n.doubleValue(); return valAsDouble < Long.MIN_VALUE || valAsDouble > Long.MAX_VALUE; } return false; } else if (Integer.class.equals(clazz)) { if (n instanceof Double || n instanceof Float) { double valAsDouble = n.doubleValue(); return valAsDouble < Integer.MIN_VALUE || valAsDouble > Integer.MAX_VALUE; } else { long valAsLong = n.longValue(); return valAsLong < Integer.MIN_VALUE || valAsLong > Integer.MAX_VALUE; } } else if (Short.class.equals(clazz)) { if (n instanceof Double || n instanceof Float) { double valAsDouble = n.doubleValue(); return valAsDouble < Short.MIN_VALUE || valAsDouble > Short.MAX_VALUE; } else { long valAsLong = n.longValue(); return valAsLong < Short.MIN_VALUE || valAsLong > Short.MAX_VALUE; } } else if (Byte.class.equals(clazz)) { if (n instanceof Double || n instanceof Float) { double valAsDouble = n.doubleValue(); return valAsDouble < Byte.MIN_VALUE || valAsDouble > Byte.MAX_VALUE; } else { long valAsLong = n.longValue(); return valAsLong < Byte.MIN_VALUE || valAsLong > Byte.MAX_VALUE; } } return false; } @SuppressWarnings("unchecked") private static <T> T castObject(final Class<T> tClass, final Object obj) throws DataReaderException { if (obj == null) { return null; } try { if (Number.class.isAssignableFrom(tClass) && obj instanceof Number) { Number objAsNumber = (Number) obj; if (DataReader.checkOverflow(tClass, objAsNumber)) { throw new DataReaderException("Value overflows type " + tClass); } if (Byte.class.equals(tClass)) { return (T) Byte.valueOf(objAsNumber.byteValue()); } else if (Short.class.equals(tClass)) { return (T) Short.valueOf(objAsNumber.shortValue()); } else if (Integer.class.equals(tClass)) { return (T) Integer.valueOf(objAsNumber.intValue()); } else if (Long.class.equals(tClass)) { return (T) Long.valueOf(objAsNumber.longValue()); } else if (Double.class.equals(tClass)) { return (T) Double.valueOf(objAsNumber.doubleValue()); } else if (Float.class.equals(tClass)) { return (T) Float.valueOf(objAsNumber.floatValue()); } } else if (String.class.equals(tClass) && obj instanceof String) { return (T) obj; } else { return tClass.cast(obj); } } catch (ClassCastException ex) { throw new DataReaderException(ex); } return null; } /** * Gets the value for {@code key} from {@code map} as a custom object. * * @param <T> Custom type * @param tClass Custom class * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code T} value associated with {@code key} or null if {@code key} is not present in * {@code map} * @throws DataReaderException if value is not gettable as a {@code T} */ private static <T> T getTypedObject( final Class<T> tClass, final Map<String, ?> map, final String key) throws DataReaderException { if (map == null || key == null) { throw new DataReaderException("Map or key is null"); } Object value = map.get(key); return castObject(tClass, value); } /** * Gets the value for {@code key} from {@code map} as a custom object or returns default value * * @param <T> Custom type * @param tClass Custom class * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code T} value to return in case of failure. Can be null. * @return {@code T} value associated with {@code key}, or {@code fallback} if value is not * gettable as a {@code T} */ private static <T> T optTypedObject( final Class<T> tClass, final Map<String, ?> map, final String key, final T fallback) { T ret = null; try { ret = getTypedObject(tClass, map, key); } catch (DataReaderException ex) { } return ret != null ? ret : fallback; } /** * Gets the value for {@code key} from {@code map} as a {@code Map<String, T>} * * @param <T> Custom type * @param tClass Custom class * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code Map<String, T>} Map associated with {@code key} or null if {@code key} is not * present in {@code map} * @throws DataReaderException if value is not gettable as a {@code Map<String,T>} */ @SuppressWarnings("unchecked") public static <T> Map<String, T> getTypedMap( final Class<T> tClass, final Map<String, ?> map, final String key) throws DataReaderException { if (tClass == null) { throw new DataReaderException("Class type is null"); } if (map == null || key == null) { throw new DataReaderException("Map or key is null"); } Object value = map.get(key); if (value == null) { return null; } if (!(value instanceof Map)) { throw new DataReaderException("Value is not a map"); } Map<?, ?> valueAsMap = (Map<?, ?>) value; for (Map.Entry<?, ?> kv : valueAsMap.entrySet()) { if (!(kv.getKey() instanceof String)) { throw new DataReaderException("Map entry is not of expected type"); } if (kv.getValue() != null && !tClass.isInstance(kv.getValue())) { throw new DataReaderException("Map entry is not of expected type"); } } return (Map<String, T>) valueAsMap; } /** * Gets the value for {@code key} from {@code map} as a {@code Map<String, T>} or returns * default value * * @param <T> Custom type * @param tClass Custom class * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code Map<String, T>} value to return in case of failure. Can be null. * @return {@code Map<String, T>} Map associated with {@code key}, or {@code fallback} if value * is not gettable as a {@code Map<String, T>} */ public static <T> Map<String, T> optTypedMap( final Class<T> tClass, final Map<String, ?> map, final String key, final Map<String, T> fallback) { Map<String, T> ret = null; try { ret = getTypedMap(tClass, map, key); } catch (DataReaderException ex) { } return ret != null ? ret : fallback; } /** * Gets the value for {@code key} from {@code map} as a {@code List<T>} * * @param <T> Custom type * @param tClass Custom class * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code List<T>} List associated with {@code key} or null if {@code key} is not * present in {@code map} * @throws DataReaderException if value is not gettable as a {@code List<T>} */ @SuppressWarnings("unchecked") public static <T> List<T> getTypedList( final Class<T> tClass, final Map<String, ?> map, final String key) throws DataReaderException { if (tClass == null) { throw new DataReaderException("Class type is null"); } if (map == null || key == null) { throw new DataReaderException("Map or key is null"); } Object value = map.get(key); if (value == null) { return null; } if (!(value instanceof List)) { throw new DataReaderException("Value is not a list"); } List<?> valueAsList = (List<?>) value; for (Object obj : valueAsList) { if (!tClass.isInstance(obj)) { throw new DataReaderException("List entry is not of expected type"); } } return (List<T>) valueAsList; } /** * Gets the value for {@code key} from {@code map} as a {@code List<T>} or returns default value * * @param <T> Custom type * @param tClass Custom class * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code List<T>} value to return in case of failure. Can be null. * @return {@code List<T>} List associated with {@code key}, or {@code fallback} if value is not * gettable as a {@code List<T>} */ public static <T> List<T> optTypedList( final Class<T> tClass, final Map<String, ?> map, final String key, final List<T> fallback) { List<T> ret = null; try { ret = getTypedList(tClass, map, key); } catch (DataReaderException ex) { } return ret != null ? ret : fallback; } /** * Gets the value for {@code key} from {@code map} as a {@code List<Map<String, T>>} * * @param <T> Custom type * @param tClass Custom class * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code List<Map<String, T>>} List associated with {@code key} or null if {@code key} * is not present in {@code map} * @throws DataReaderException if value is not gettable as a {@code List<Map<String, T>>} */ @SuppressWarnings("unchecked") public static <T> List<Map<String, T>> getTypedListOfMap( final Class<T> tClass, final Map<String, ?> map, final String key) throws DataReaderException { if (tClass == null) { throw new DataReaderException("Class type is null"); } if (map == null || key == null) { throw new DataReaderException("Map or key is null"); } Object value = map.get(key); if (value == null) { return null; } if (!(value instanceof List)) { throw new DataReaderException("Value is not a list"); } List<?> valueAsList = (List<?>) value; for (Object obj : valueAsList) { if (!(obj instanceof Map)) { throw new DataReaderException("List entry is not of expected type"); } Map<?, ?> objAsMap = (Map<?, ?>) obj; for (Map.Entry<?, ?> kv : objAsMap.entrySet()) { if (!(kv.getKey() instanceof String)) { throw new DataReaderException("Map entry is not of expected type"); } if (kv.getValue() != null && !tClass.isInstance(kv.getValue())) { throw new DataReaderException("Map entry is not of expected type"); } } } return (List<Map<String, T>>) valueAsList; } /** * Gets the value for {@code key} from {@code map} as a {@code List<Map<String, T>>} or returns * default value * * @param <T> Custom type * @param tClass Custom class * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code List<Map<String, T>>} value to return in case of failure. Can be null. * @return {@code List<Map<String, T>>} List associated with {@code key}, or {@code fallback} if * value is not gettable as a {@code List<Map<String, T>>} */ public static <T> List<Map<String, T>> optTypedListOfMap( final Class<T> tClass, final Map<String, ?> map, final String key, final List<Map<String, T>> fallback) { List<Map<String, T>> ret = null; try { ret = getTypedListOfMap(tClass, map, key); } catch (DataReaderException ex) { } return ret != null ? ret : fallback; } /** * Gets the value for {@code key} from {@code map} as a {@code boolean} * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code boolean} value associated with {@code key} * @throws DataReaderException if value is not gettable as a {@code boolean} or if {@code key} * is not present in {@code map} */ public static boolean getBoolean(final Map<String, ?> map, final String key) throws DataReaderException { Boolean ret = getTypedObject(Boolean.class, map, key); if (ret == null) { throw new DataReaderException("Map contains null value for key"); } return ret; } /** * Gets the value for {@code key} from {@code map} as a {@code boolean} or returns default value * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code boolean} value to return in case of failure. Can be null. * @return {@code boolean} value associated with {@code key}, or {@code fallback} if value is * not gettable as a {@code boolean} */ public static boolean optBoolean( final Map<String, ?> map, final String key, final boolean fallback) { return optTypedObject(Boolean.class, map, key, fallback); } /** * Gets the value for {@code key} from {@code map} as an {@code int} * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code int} value associated with {@code key} * @throws DataReaderException if value is not gettable as an {@code int} or if {@code key} is * not present in {@code map} */ public static int getInt(final Map<String, ?> map, final String key) throws DataReaderException { Integer ret = getTypedObject(Integer.class, map, key); if (ret == null) { throw new DataReaderException("Map contains null value for key"); } return ret; } /** * Gets the value for {@code key} from {@code map} as an {@code int} or returns default value * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code int} value to return in case of failure. Can be null. * @return {@code int} value associated with {@code key}, or {@code fallback} if value is not * gettable as a {@code int} */ public static int optInt(final Map<String, ?> map, final String key, final int fallback) { return optTypedObject(Integer.class, map, key, fallback); } /** * Gets the value for {@code key} from {@code map} as an {@code long} * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code long} value associated with {@code key} * @throws DataReaderException if value is not gettable as an {@code long} or if {@code key} is * not present in {@code map} */ public static long getLong(final Map<String, ?> map, final String key) throws DataReaderException { Long ret = getTypedObject(Long.class, map, key); if (ret == null) { throw new DataReaderException("Map contains null value for key"); } return ret; } /** * Gets the value for {@code key} from {@code map} as an {@code long} or returns default value * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code long} value to return in case of failure. Can be null. * @return {@code long} value associated with {@code key}, or {@code fallback} if value is not * gettable as a {@code long} */ public static long optLong(final Map<String, ?> map, final String key, final long fallback) { return optTypedObject(Long.class, map, key, fallback); } /** * Gets the value for {@code key} from {@code map} as an {@code float} * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code float} value associated with {@code key} * @throws DataReaderException if value is not gettable as an {@code float} or if {@code key} is * not present in {@code map} */ public static float getFloat(final Map<String, ?> map, final String key) throws DataReaderException { Float ret = getTypedObject(Float.class, map, key); if (ret == null) { throw new DataReaderException("Map contains null value for key"); } return ret; } /** * Gets the value for {@code key} from {@code map} as an {@code float} or returns default value * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code float} value to return in case of failure. Can be null. * @return {@code float} value associated with {@code key}, or {@code fallback} if value is not * gettable as a {@code float} */ public static float optFloat(final Map<String, ?> map, final String key, final float fallback) { return optTypedObject(Float.class, map, key, fallback); } /** * Gets the value for {@code key} from {@code map} as an {@code double} * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code double} value associated with {@code key} * @throws DataReaderException if value is not gettable as an {@code double} or if {@code key} * is not present in {@code map} */ public static double getDouble(final Map<String, ?> map, final String key) throws DataReaderException { Double ret = getTypedObject(Double.class, map, key); if (ret == null) { throw new DataReaderException("Map contains null value for key"); } return ret; } /** * Gets the value for {@code key} from {@code map} as an {@code double} or returns default value * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code double} value to return in case of failure. Can be null. * @return {@code double} value associated with {@code key}, or {@code fallback} if value is not * gettable as a {@code double} */ public static double optDouble( final Map<String, ?> map, final String key, final double fallback) { return optTypedObject(Double.class, map, key, fallback); } /** * Gets the value for {@code key} from {@code map} as an {@code String} * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code String} value associated with {@code key} or null if {@code key} is not * present in {@code map} * @throws DataReaderException if value is not gettable as an {@code String} */ public static String getString(final Map<String, ?> map, final String key) throws DataReaderException { return getTypedObject(String.class, map, key); } /** * Gets the value for {@code key} from {@code map} as a {@code String} or returns default value * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code String} value to return in case of failure. Can be null. * @return {@code String} value associated with {@code key}, or {@code fallback} if value is not * gettable as a {@code String} */ public static String optString( final Map<String, ?> map, final String key, final String fallback) { return optTypedObject(String.class, map, key, fallback); } /** * Gets the value for {@code key} from {@code map} as a {@code Map<String, String>} * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code Map<String, String>} Map associated with {@code key} or null if {@code key} is * not present in {@code map} * @throws DataReaderException if value is not gettable as a {@code Map<String, String>} */ public static Map<String, String> getStringMap(final Map<String, ?> map, final String key) throws DataReaderException { return getTypedMap(String.class, map, key); } /** * Gets the value for {@code key} from {@code map} as a {@code Map<String, String>} or returns * default value * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code Map<String, String>} value to return in case of failure. Can be null. * @return {@code Map<String, String>} value associated with {@code key}, or {@code fallback} if * value is not gettable as a {@code Map<String, String>} */ public static Map<String, String> optStringMap( final Map<String, ?> map, final String key, final Map<String, String> fallback) { return optTypedMap(String.class, map, key, fallback); } /** * Gets the value for {@code key} from {@code map} as a {@code List<String>} * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @return {@code List<String>} List associated with {@code key} or null if {@code key} is not * present in {@code map} * @throws DataReaderException if value is not gettable as a {@code List<String>} */ public static List<String> getStringList(final Map<String, ?> map, final String key) throws DataReaderException { return getTypedList(String.class, map, key); } /** * Gets the value for {@code key} from {@code map} as a {@code List<String>} or returns default * value * * @param map {@code Map} map to fetch data * @param key {@code String} key to fetch * @param fallback {@code List<String>} value to return in case of failure. Can be null. * @return {@code List<String>} List associated with {@code key}, or {@code fallback} if value * is not gettable as a {@code List<String>} */ public static List<String> optStringList( final Map<String, ?> map, final String key, final List<String> fallback) { return optTypedList(String.class, map, key, fallback); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/SerialWorkDispatcher.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util import androidx.annotation.VisibleForTesting import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.services.Log import java.lang.Exception import java.lang.IllegalStateException import java.util.Queue import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.Future /** * Provides a template for processing a queue of work items serially. Allows adding new work items * while the another item is being processed. Aims to separate the lifecycle of the worker thread * that process work items with the queue that they are fetched from to allow sub-classes to be * agnostic of worker thread management. */ open class SerialWorkDispatcher<T>(private val name: String, private val workHandler: WorkHandler<T>) { private companion object { private const val LOG_TAG = "SerialWorkDispatcher" } /** * Represents the state of the [SerialWorkDispatcher]. */ enum class State { /** * Indicates that the dispatcher has not yet started. * New work will be accepted but not executed until started. */ NOT_STARTED, /** * Indicates that the dispatcher has been started and work will * be accepted. */ ACTIVE, /** * Indicates that the dispatcher has been paused. New work will * be accepted but not executed until resumed */ PAUSED, /** * Indicates that the dispatcher has been shutdown and no more work * will be accepted. */ SHUTDOWN } /** * Represents the functional interface that is responsible for doing the desired work on each item of the [workQueue]. * [WorkHandler.doWork] is called from the background worker thread that the [SerialWorkDispatcher] maintains. */ fun interface WorkHandler<W> { /** * Handles processing on [item] * * @param item the work item which is dispatched for processing. * @return [Boolean] A boolean variable denoting whether the [item] has completed processing. * If [WorkHandler.doWork] returns false after processing an item, the [SerialWorkDispatcher] stops processing the work queue without removing the item. It restarts when * [resume] is called or a new item is enqueued. * If [WorkHandler.doWork] returns true after processing an item, it removes it from work queue and continues processing other queued items. */ fun doWork(item: W): Boolean } /** * The executor to which work is submitted for sequencing. */ private var executorService: ExecutorService = Executors.newSingleThreadExecutor() /** * Holds the work items that need to be processed by this dispatcher. */ private val workQueue: Queue<T> = ConcurrentLinkedQueue() /** * A runnable responsible for draining the work items from the [workQueue] * and processing them via [WorkHandler.doWork]. */ private val workProcessor: WorkProcessor by lazy { WorkProcessor() } /** * A handle for identifying and manipulating the state of the thread that this dispatcher owns. * Can be used to ensure that only one [workProcessor] is active at a time. */ private var workProcessorFuture: Future<*>? = null /** * Denotes the current state of the [SerialWorkDispatcher]. It is synonymous with the ability of the * [workQueue] to accept new items. Note that this is not the state of the worker-thread that this * dispatcher maintains. */ @Volatile private var state: State = State.NOT_STARTED /** * Used for guarding the "activeness" logic. */ private val activenessMutex: Any = Any() /** * The initialization job that is to be executed when the [SerialWorkDispatcher] starts (i.e * before processing any items in the [workQueue] for the first time) */ @Volatile private var initialJob: Runnable? = null /** * The initialization job that is to be executed immediately before the [SerialWorkDispatcher] shuts down. */ @Volatile private var finalJob: Runnable? = null /** * Sets a job that is will be invoked (on the thread that [SerialWorkDispatcher] maintains) * immediately when the [SerialWorkDispatcher] starts and before processing the items in the queue. * Implementers are expected to perform any one-time setup operations before processing starts. * The initial job will only be executed if set before start() is invoked. * * @param initialJob the [Runnable] that is to be invoked immediately before the [SerialWorkDispatcher] starts * processing work items */ fun setInitialJob(initialJob: Runnable) { this.initialJob = initialJob } /** * Sets a job that will be invoked ((on the thread that [SerialWorkDispatcher] maintains) * immediately before the [executorService] is shutdown as a result of [SerialWorkDispatcher.shutdown]. * Implementers are expected to perform any cleanup operations when the [SerialWorkDispatcher] * is shutdown. The final job will only be executed if set before shutdown() is invoked. * * @param finalJob the [Runnable] that is to be invoked immediately before the [SerialWorkDispatcher] shuts down */ fun setFinalJob(finalJob: Runnable) { this.finalJob = finalJob } /** * Enqueues an item to the end of the [workQueue]. Additionally, * resumes the queue processing if the [SerialWorkDispatcher] is active * (but processing was stopped earlier due to lack of work). * * @param item item that needs to be processed. * @return true if [item] has been enqueued successfully, false otherwise */ fun offer(item: T): Boolean { // Hold the activeness lock to ensure that an update to state is // not being made while a state change operation start/resume/stop is being done. synchronized(activenessMutex) { if (state == State.SHUTDOWN) return false workQueue.offer(item) if (state == State.ACTIVE) { // resume the processing the work items in the queue if necessary resume() } return true } } /** * Invoked immediately before processing the items in the queue for the first time. * Implementers are expected to perform any one-time setup operations (bound by the activeness of * [SerialWorkDispatcher]) before processing starts. */ private fun prepare() { val initTask = this.initialJob ?: return executorService.submit(initTask) } /** * Puts the [SerialWorkDispatcher] in active state and starts processing the {@link #workQueue} * if not already active. * * @return true - if [SerialWorkDispatcher] was successfully started, * false - if it is already active or was shutdown * @throws IllegalStateException when attempting to start a dispatcher after being shutdown */ fun start(): Boolean { synchronized(activenessMutex) { if (state == State.SHUTDOWN) { throw IllegalStateException("Cannot start SerialWorkDispatcher ($name). Already shutdown.") } if (state != State.NOT_STARTED) { Log.debug( CoreConstants.LOG_TAG, getTag(), "SerialWorkDispatcher ($name) has already started." ) return false } state = State.ACTIVE prepare() resume() return true } } /** * Puts the [SerialWorkDispatcher] in paused state and stops processing the {@link #workQueue} * * @return true - if [SerialWorkDispatcher] was successfully stopped, * false - if it is already stopped or was shutdown * @throws IllegalStateException when attempting to start a dispatcher after being shutdown */ fun pause(): Boolean { synchronized(activenessMutex) { if (state == State.SHUTDOWN) { throw IllegalStateException("Cannot pause SerialWorkDispatcher ($name). Already shutdown.") } if (state != State.ACTIVE) { Log.debug( CoreConstants.LOG_TAG, getTag(), "SerialWorkDispatcher ($name) is not active." ) return false } state = State.PAUSED return true } } /** * Resumes processing the work items in the [workQueue] if the [SerialWorkDispatcher] * is active and if no worker thread is actively processing the [workQueue]. * Implementers can optionally trigger work via [resume] after any changes to logic in [canWork] * now being true, without having to wait for the next item to be added. */ fun resume(): Boolean { synchronized(activenessMutex) { if (state == State.SHUTDOWN) { throw IllegalStateException("Cannot resume SerialWorkDispatcher ($name). Already shutdown.") } if (state == State.NOT_STARTED) { Log.debug( CoreConstants.LOG_TAG, getTag(), "SerialWorkDispatcher ($name) has not started." ) return false } state = State.ACTIVE val activeWorkProcessor: Future<*>? = workProcessorFuture if ((activeWorkProcessor != null && !activeWorkProcessor.isDone) || !canWork()) { // if the dispatcher is inactive or, if there is any active worker processing // the queue - do not do anything as the existing processor will process the items return true } // start the work processor workProcessorFuture = executorService.submit(workProcessor) return true } } /** * Invoked before processing each work item. Results in the worker thread being completed * if the implementer returns false. Returning false will result in "pausing" the processing (which * can later be resumed via [resume] explicitly or, when a re-evaluation of [canWork] happens when * new item is added to the [workQueue] via [offer]). * Implementers are expected to enforce any conditions that need * to be checked before performing work here. * * @return true if all conditions are met for performing work, false otherwise. */ protected open fun canWork(): Boolean { // Return true by default return true } /** * Checks if there are any work items available for processing. * * @return true if there are any available in [workQueue] work items for processing, * false otherwise */ private fun hasWork(): Boolean { return workQueue.peek() != null } /** * Removes the work item at the front (earliest queued) of the [workQueue] * * @return the work item at the front (earliest queued) of the [workQueue], null if [workQueue] is empty */ private fun removeWorkItem(): T? { return workQueue.poll() } /** * Peeks the work item at the front (earliest queued) of the [workQueue] * * @return the work item at the front (earliest queued) of the [workQueue], null if [workQueue] is empty */ private fun peekWorkItem(): T? { return workQueue.peek() } /** * Invoked before the executor service maintained by this class is shutdown as a result of [shutdown]. */ private fun cleanup() { val cleanupTask = finalJob ?: return executorService.submit(cleanupTask) } /** * Puts the [SerialWorkDispatcher] into inactive state and clears the [workQueue]. * Calling [resume] or [start] will have no effect on the state of the [SerialWorkDispatcher] after * this method is invoked. */ fun shutdown() { synchronized(activenessMutex) { if (state == State.SHUTDOWN) return state = State.SHUTDOWN // Cancel active work processing (if any) val activeTask: Future<*>? = workProcessorFuture activeTask?.cancel(true) workProcessorFuture = null workQueue.clear() } cleanup() // It is necessary and sufficient to call executorService.shutdown instead of executorService.shutdownNow() // for the following reasons: // - At this point, the state of the dispatcher is SHUTDOWN, and no new work can be submitted to the executorService // - prepare() and cleanup() are serialized using [activenessMutex] and guarded by [state]. This prevents them from // executing out of order (therefore cleanup is always executed after prepare for a valid invocation). // - executorService.shutdown() will allow [teardownJob] to execute before shutting down completely. executorService.shutdown() } fun getState(): State { return state } private fun getTag() = "$LOG_TAG-$name" /** * A runnable responsible for looping through the work items maintained by [SerialWorkDispatcher] * in its [workQueue] */ @VisibleForTesting internal inner class WorkProcessor : Runnable { override fun run() { // flag representing whether processing should be auto resumed after the loop ends var autoResume = true // Perform work only if the dispatcher is unblocked and there are // items in the queue to perform work on. while (!Thread.interrupted() && state == State.ACTIVE && canWork() && hasWork()) { try { val workItem = peekWorkItem() // this return exists for syntactical correctness. We reached here after // verifying that there is work via hasWork() and work cannot be removed // outside of the WorkProcessor. So there should exist at least one work // item when we reach here. ?: return if (workHandler.doWork(workItem)) { // Handler has successfully processed the work item, remove and try processing the next item removeWorkItem() } else { // Work handler cannot process the work item, wait until next item. // Do not auto resume here. Auto resuming will cause aggressive retries. autoResume = false break } } catch (exception: Exception) { Thread.currentThread().interrupt() Log.warning( CoreConstants.LOG_TAG, getTag(), "Exception encountered while processing item. $exception" ) } } synchronized(activenessMutex) { // At this point the work processor future cannot be null because it refers to // this task (only one of which exists at a time). // However, there may be a case where logic in resume() bails on scheduling a new // work processor because this task is still not "done". Overcome that race by // checking the state of the queue here and invoking resume here. workProcessorFuture = null if (autoResume && state == State.ACTIVE && hasWork()) { Log.trace( CoreConstants.LOG_TAG, getTag(), "Auto resuming work processor." ) resume() } } } } @VisibleForTesting fun setExecutorService(executorService: ExecutorService) { this.executorService = executorService } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/TimeUtils.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util import java.lang.Exception import java.text.DateFormat import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.TimeZone object TimeUtils { private const val MILLISECONDS_PER_SECOND = 1000L private const val ISO8601_TIMEZONE_ISO8601_UTCZ_PRECISION_MILLISECOND = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" private const val ISO8601_TIMEZONE_ISO8601_3X_PRECISION_SECOND = "yyyy-MM-dd'T'HH:mm:ssXXX" private const val ISO8601_TIMEZONE_ISO8601_2X_PRECISION_SECOND = "yyyy-MM-dd'T'HH:mm:ssXX" private const val ISO8601_FULL_DATE = "yyyy-MM-dd" private const val RFC2822_DATE_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z" /** * Gets current unix timestamp in seconds. * * @return {code long} current timestamp */ @JvmStatic fun getUnixTimeInSeconds(): Long { return System.currentTimeMillis() / MILLISECONDS_PER_SECOND } /** * Gets the ISO 8601 formatted with colon time zone, second precision date `String` * for the provide date using the system local time zone. * * Date pattern used is [ISO8601_TIMEZONE_ISO8601_3X_PRECISION_SECOND] * which has timezone ISO 8601 'XXX' pattern, which gives a timezone of ex: "-07:00" ("Z" for UTC +0) * Ex: (device in time zone "America/Los_Angeles") Wed Nov 30 11:53:09.497 GMT-07:00 2022 -> 2022-11-30T11:53:09-07:00 * * @param date the [Date] to apply the formatting to; defaults to the current [Date] * @return date [String] formatted as ISO 8601 with colon time zone, second precision */ @JvmStatic @JvmOverloads fun getISO8601Date(date: Date = Date()): String { return getFormattedDate(date, ISO8601_TIMEZONE_ISO8601_3X_PRECISION_SECOND) ?: "" } /** * Gets the ISO 8601 formatted with no colon time zone, second precision date `String` * for the provide date using the system local time zone. * * Date pattern used is [ISO8601_TIMEZONE_ISO8601_2X_PRECISION_SECOND] * which has timezone ISO 8601 'XX' pattern, which gives a timezone of ex: "-0700" ("Z" for UTC +0) * Ex: (device in time zone "America/Los_Angeles") Wed Nov 30 11:53:09.497 GMT-07:00 2022 -> 2022-11-30T11:53:09-0700 * * @param date the [Date] to apply the formatting to; defaults to the current [Date] * @return date [String] formatted as ISO 8601 with no colon time zone, second precision */ @JvmStatic @JvmOverloads fun getISO8601DateNoColon(date: Date = Date()): String { return getFormattedDate(date, ISO8601_TIMEZONE_ISO8601_2X_PRECISION_SECOND) ?: "" } /** * Gets the ISO 8601 formatted with UTC(Z) time zone, millisecond precision date `String` for the * provided date using the UTC +0 time zone. * * Date pattern used is [ISO8601_TIMEZONE_ISO8601_UTCZ_PRECISION_MILLISECOND] * which has timezone ISO 8601 'Z' char terminator, which gives a timezone of 'Z'. * Ex: Wed Nov 30 11:53:09.497 GMT-07:00 2022 -> 2022-11-30T18:53:09.497Z (notice the hour shift because the date must be evaluated from UTC +0) * * Note that ISO 8601 requires date strings terminating with the char 'Z' to be in the time zone UTC +0 (no offset). * * AMSDK-10273 :: ExEdge requires time zone offset formatted in form [+-]HH:MM. * * @param date the [Date] to apply the formatting to; defaults to the current [Date] * @return date [String] formatted as ISO 8601 with UTC(Z) time zone, millisecond precision */ @JvmStatic @JvmOverloads fun getISO8601UTCDateWithMilliseconds(date: Date = Date()): String { return getFormattedDate(date, ISO8601_TIMEZONE_ISO8601_UTCZ_PRECISION_MILLISECOND, TimeZone.getTimeZone("GMT")) ?: "" } /** * Gets the ISO 8601 formatted full date `String` for the provided date using the system local time zone. * * Date pattern used is [ISO8601_FULL_DATE] * Ex: Wed Nov 30 11:53:09.497 GMT-07:00 2022 -> 2022-11-30 * * @param date the [Date] to apply the formatting to; defaults to the current [Date] * @return date [String] formatted as ISO 8601 full date, using system local time zone */ @JvmStatic @JvmOverloads fun getISO8601FullDate(date: Date = Date()): String { return getFormattedDate(date, ISO8601_FULL_DATE) ?: "" } /** * Parses the RFC-2822 formatted date string [rfc2822Date] into a [Date] * @param rfc2822Date RFC-2822 formatted date string to be parsed * @param timeZone the timezone that should be used * @param locale the locale whose date format symbols should be used * @return a valid date from the RF-2822 date if successful, null otherwise */ @JvmStatic fun parseRFC2822Date(rfc2822Date: String?, timeZone: TimeZone, locale: Locale): Date? { if (rfc2822Date == null) return null val rfc2822formatter: DateFormat = SimpleDateFormat(RFC2822_DATE_PATTERN, locale) rfc2822formatter.timeZone = timeZone return try { rfc2822formatter.parse(rfc2822Date) ?: Date() } catch (e: Exception) { return null } } /** * Converts the epoch into a RFC-2822 date string pattern - [RFC2822_DATE_PATTERN] * @param epoch the epoch (milliseconds) that should be converted to [Date] * @param timeZone the timezone that should be used * @param locale the locale whose date format symbols should be used * @return a RFC-2822 formatted date string for the epoch provided */ @JvmStatic fun getRFC2822Date(epoch: Long, timeZone: TimeZone, locale: Locale): String { val rfc2822formatter: DateFormat = SimpleDateFormat(RFC2822_DATE_PATTERN, locale) rfc2822formatter.timeZone = timeZone return rfc2822formatter.format(epoch) } /** * Gets the formatted date `String` for the passed in date; if no date passed in, uses current `Date()` * * @param date the [Date] to apply the formatting to * @param pattern the pattern [String] to use to format the date * @param timeZone the [TimeZone] to evaluate the formatted date from; defaults to device time zone if not specified * @return the formatted date [String], null if formatting fails */ private fun getFormattedDate(date: Date, pattern: String, timeZone: TimeZone? = null): String? { // AMSDK-8374 - // we should explicitly ignore the device's locale when formatting an ISO 8601 timestamp val posixLocale = Locale(Locale.US.language, Locale.US.country, "POSIX") val dateFormat: DateFormat = SimpleDateFormat(pattern, posixLocale) if (timeZone != null) { dateFormat.timeZone = timeZone } return dateFormat.format(date) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/EventDataUtils.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util; import com.adobe.marketing.mobile.internal.CoreConstants; import com.adobe.marketing.mobile.services.Log; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; /** * Utility to clone event data which is represented as {@code Map<String, Object>}. Currently * supports cloning values which are Boolean, Byte, Short, Integer, Long, Float, Double, BigDecimal, * BigInteger, Character, String, UUID, Maps and Collections. */ public class EventDataUtils { private static final int MAX_DEPTH = 256; private static final String LOG_SOURCE = "EventDataUtils"; private enum CloneMode { ImmutableContainer, MutableContainer, } private static final Set<Class<?>> immutableClasses; static { immutableClasses = new HashSet<>(); immutableClasses.add(Boolean.class); immutableClasses.add(Byte.class); immutableClasses.add(Short.class); immutableClasses.add(Integer.class); immutableClasses.add(Long.class); immutableClasses.add(Float.class); immutableClasses.add(Double.class); immutableClasses.add(BigDecimal.class); immutableClasses.add(BigInteger.class); immutableClasses.add(Character.class); immutableClasses.add(String.class); immutableClasses.add(UUID.class); } private EventDataUtils() {} private static Object cloneObject(final Object obj, final CloneMode mode, final int depth) throws CloneFailedException { if (obj == null) { return null; } if (depth > MAX_DEPTH) { throw new CloneFailedException(CloneFailedException.Reason.MAX_DEPTH_REACHED); } final Class<?> objClass = obj.getClass(); if (immutableClasses.contains(objClass)) { return obj; } if (obj instanceof Map) { return cloneMap((Map<?, ?>) obj, mode, depth); } else if (obj instanceof Collection) { return cloneCollection((Collection<?>) obj, mode, depth); } else if (obj.getClass().isArray()) { return cloneArray(obj, mode, depth); } else { Log.trace( CoreConstants.LOG_TAG, LOG_SOURCE, "Cannot clone object of type: %s", objClass.getSimpleName()); throw new CloneFailedException(CloneFailedException.Reason.UNSUPPORTED_TYPE); } } private static Map<String, Object> cloneMap( final Map<?, ?> map, final CloneMode mode, final int depth) throws CloneFailedException { if (map == null) return null; Map<String, Object> ret = new HashMap<>(); for (Map.Entry<?, ?> kv : map.entrySet()) { Object key = kv.getKey(); if (key instanceof String) { try { Object clonedValue = cloneObject(kv.getValue(), mode, depth + 1); ret.put(key.toString(), clonedValue); } catch (CloneFailedException e) { if (e.getReason() != CloneFailedException.Reason.UNSUPPORTED_TYPE) { throw e; } Log.trace( CoreConstants.LOG_TAG, LOG_SOURCE, "cloneMap - Skipped cloning key %s due to %s", key, e.getMessage()); } } } return mode == CloneMode.ImmutableContainer ? Collections.unmodifiableMap(ret) : ret; } private static Collection<Object> cloneCollection( final Collection<?> collection, final CloneMode mode, final int depth) throws CloneFailedException { if (collection == null) return null; List<Object> ret = new ArrayList<>(); for (Object element : collection) { try { Object clonedElement = cloneObject(element, mode, depth + 1); ret.add(clonedElement); } catch (CloneFailedException e) { if (e.getReason() != CloneFailedException.Reason.UNSUPPORTED_TYPE) { throw e; } Log.trace( CoreConstants.LOG_TAG, LOG_SOURCE, "cloneCollection - Skipped cloning element due to %s", e.getMessage()); } } return mode == CloneMode.ImmutableContainer ? Collections.unmodifiableList(ret) : ret; } private static Collection<Object> cloneArray( final Object array, final CloneMode mode, final int depth) throws CloneFailedException { if (array == null) return null; List<Object> ret = new ArrayList<>(); int length = Array.getLength(array); for (int i = 0; i < length; ++i) { try { ret.add(cloneObject(Array.get(array, i), mode, depth + 1)); } catch (CloneFailedException e) { if (e.getReason() != CloneFailedException.Reason.UNSUPPORTED_TYPE) { throw e; } Log.trace( CoreConstants.LOG_TAG, LOG_SOURCE, "cloneArray - Skipped cloning element due to %s", e.getMessage()); } } return mode == CloneMode.ImmutableContainer ? Collections.unmodifiableList(ret) : ret; } /** * Deep clones the provided map. Support cloning values which are basic types, maps and * collections. <br> * Values which are {@code Map<?, ?>} are cloned as {@code HashMap<String, Object>}. * * <ul> * <li>Entry with null key is dropped. * <li>Entry with non {@code String} key is converted to entry with {@code String} key by * calling {@link Object#toString()} method. * </ul> * * Values which are {@code Collection<?>} are cloned as {@code ArrayList<Object>}. * * @param map map to be cloned * @return Cloned map * @throws CloneFailedException if object depth exceeds {@value EventDataUtils#MAX_DEPTH} or * contains unsupported type. */ public static Map<String, Object> clone(final Map<String, ?> map) throws CloneFailedException { return cloneMap(map, CloneMode.MutableContainer, 0); } /** * Deep clones the provided map. Support cloning values which are basic types, maps and * collections. <br> * Values which are {@code Map<?, ?>} are cloned as unmodifiable {@code HashMap<String, * Object>}. * * <ul> * <li>Entry with null key is dropped. * <li>Entry with non {@code String} key is converted to entry with {@code String} key by * calling {@link Object#toString()} method. * </ul> * * Values which are {@code Collection<?>} are cloned as unmodifiable {@code ArrayList<Object>}. * * @param map map to be cloned * @return Cloned immutable map * @throws CloneFailedException if object depth exceeds {@value EventDataUtils#MAX_DEPTH} or * contains unsupported type. */ public static Map<String, Object> immutableClone(final Map<String, ?> map) throws CloneFailedException { return cloneMap(map, CloneMode.ImmutableContainer, 0); } /** * Casts generic map {@code Map<?, ?>} to {@code HashMap<String, Object>} * * <ul> * <li>Entry with null and non {@code String} key is dropped. * <li>Entry withnon {@code String} key is dropped * </ul> * * @param map map to be cast * @return map cast to type {@code Map<String, Object>} */ @SuppressWarnings("unchecked") public static Map<String, Object> castFromGenericType(final Map<?, ?> map) { if (map == null) return null; for (Map.Entry<?, ?> entry : map.entrySet()) { if (!(entry.getKey() instanceof String)) { return null; } } return (Map<String, Object>) map; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/UrlUtils.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util; import android.net.Uri; import com.adobe.marketing.mobile.internal.util.UrlEncoder; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; public final class UrlUtils { private UrlUtils() {} /** * Check if the given {@code String} is a valid URL. * * <p>It uses {@link URL} class to identify that. * * @param stringUrl URL that needs to be tested * @return return a {@code boolean} indicating if the given parameter is a valid URL */ public static boolean isValidUrl(final String stringUrl) { if (StringUtils.isNullOrEmpty(stringUrl)) { return false; } try { new URL(stringUrl); return true; } catch (MalformedURLException ex) { return false; } } /** * Encodes an URL given as {@code String}. * * @param unencodedString nullable {@link String} value to be encoded * @return the encoded {@code String} */ public static String urlEncode(final String unencodedString) { return UrlEncoder.urlEncode(unencodedString); } /** * Extras query parameters as a {@code Map} * * @param uri the URI string to extract parameters * @return a {@code Map} of query parameters */ public static Map<String, String> extractQueryParameters(final String uri) { try { Map<String, String> map = new HashMap<>(); Uri uriObject = Uri.parse(uri); for (String name : uriObject.getQueryParameterNames()) { String value = uriObject.getQueryParameter(name); if (!StringUtils.isNullOrEmpty(name) && !StringUtils.isNullOrEmpty(value)) { map.put(name, value); } } return map; } catch (Exception e) { return null; } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/DefaultPresentationUtilityProvider.kt
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util import android.app.Activity import android.app.Application import com.adobe.marketing.mobile.services.ServiceProvider import com.adobe.marketing.mobile.services.ui.PresentationUtilityProvider import java.io.InputStream /** * Default implementation of [PresentationUtilityProvider] that uses the [ServiceProvider] * to relay the calls to the appropriate services. */ class DefaultPresentationUtilityProvider : PresentationUtilityProvider { override fun getApplication(): Application? { return ServiceProvider.getInstance().appContextService.application } override fun getCurrentActivity(): Activity? { return ServiceProvider.getInstance().appContextService.currentActivity } override fun getCachedContent(cacheName: String, key: String): InputStream? { val cacheResult = ServiceProvider.getInstance().cacheService.get(cacheName, key) return cacheResult?.data } override fun openUri(uri: String): Boolean { return ServiceProvider.getInstance().uriService.openUri(uri) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/URLBuilder.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util; import com.adobe.marketing.mobile.internal.CoreConstants; import com.adobe.marketing.mobile.services.Log; import java.net.URL; import java.util.Map; /** A class providing a better way to construct a url. */ public class URLBuilder { public enum EncodeType { NONE(1), ENCODE(2); public final int id; EncodeType(final int identifier) { id = identifier; } } private boolean sslEnabled = true; private String path; private String server; private String query; /** constructor */ public URLBuilder() { this.path = ""; this.query = ""; this.server = ""; } /** * set whether SSL is enabled * * @param sslEnabled the boolean flag to indicated whether SSL is enabled * @return this */ public URLBuilder enableSSL(final boolean sslEnabled) { this.sslEnabled = sslEnabled; return this; } /** * set the server address * * @param server server address * @return this */ public URLBuilder setServer(final String server) { this.server = server; return this; } /** * add path to the url, should not include '/' in the string * * @param newPath path string without '/' * @return this */ public URLBuilder addPath(final String newPath) { if (newPath == null || newPath.length() == 0) { return this; } this.path = this.path + "/" + UrlUtils.urlEncode(newPath); return this; } /** * add multiple query parameters * * @param parameters the map containing query parameters * @return this */ public URLBuilder addQueryParameters(final Map<String, String> parameters) { if (parameters == null || parameters.size() == 0) { return this; } for (Map.Entry<String, String> entry : parameters.entrySet()) { this.addQueryParameter(entry.getKey(), entry.getValue()); } return this; } /** * add one query parameter with key/value pair, both key and value will be encoded * * @param key the key of the query parameter * @param value the value of the query parameter * @return this */ public URLBuilder addQueryParameter(final String key, final String value) { if (StringUtils.isNullOrEmpty(key) || StringUtils.isNullOrEmpty(value)) { return this; } return this.addQuery( UrlUtils.urlEncode(key) + "=" + UrlUtils.urlEncode(value), EncodeType.NONE); } /** * add a whole string as a query in the url, the string will be encoded * * @param newQuery the query string to be added to the url * @return this */ public URLBuilder addQuery(final String newQuery) { return this.addQuery(newQuery, EncodeType.ENCODE); } /** * add a whole string as a query in the url * * @param newQuery the query string to be added to the url * @param encodeType encode type to be used to encode the query * @return this */ public URLBuilder addQuery(final String newQuery, final EncodeType encodeType) { if (newQuery == null || newQuery.length() == 0) { return this; } String encodedQuery = encodeType == EncodeType.ENCODE ? UrlUtils.urlEncode(newQuery) : newQuery; if (this.query == null || this.query.length() == 0) { this.query = encodedQuery; } else { this.query = this.query + "&" + encodedQuery; } return this; } /** * build the url string based on all the data provided before * * @return the url string */ public String build() { if (StringUtils.isNullOrEmpty(this.server)) { Log.error( "URLBuilder", "Failed to generate the URL for (server:%s, path:%s, query:%s)", this.server, this.path, this.query); return null; } boolean hasQuery = this.query != null && this.query.length() > 0; final String urlString = String.format( "%s://%s%s%s%s", this.sslEnabled ? "https" : "http", this.server, this.path, hasQuery ? "?" : "", this.query); try { new URL(urlString).toURI(); } catch (Exception e) { Log.error( CoreConstants.LOG_TAG, "URLBuilder", "Failed to generate the URL for (server:%s, path:%s, query:%s) (%s)", this.server, this.path, this.query, e); return null; } return urlString; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/SQLiteUtils.java
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util; import android.database.sqlite.SQLiteDatabase; import com.adobe.marketing.mobile.internal.CoreConstants; import com.adobe.marketing.mobile.services.Log; import com.adobe.marketing.mobile.services.ServiceProvider; import java.io.File; public class SQLiteUtils { private SQLiteUtils() {} private static final String LOG_SOURCE = "SQLiteUtils"; /** * Deletes the database files in the Application's cache folder. * * @param fileName the file name to be deleted * @return true, if the file is successfully deleted; false otherwise */ public static boolean deleteDBFromCacheDir(final String fileName) { try { final File cacheDir = ServiceProvider.getInstance().getDeviceInfoService().getApplicationCacheDir(); if (cacheDir == null || StringUtils.isNullOrEmpty(fileName)) { return false; } final File databaseFile = new File(cacheDir, fileName); return SQLiteDatabase.deleteDatabase(databaseFile); } catch (Exception e) { Log.debug( CoreConstants.LOG_TAG, LOG_SOURCE, "Failed to delete (%s) in cache folder.", fileName); return false; } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/EventUtils.kt
/* Copyright 2024 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ @file:JvmName("EventUtils") // Allows Java callers to use EventUtils.<> instead of EventUtilsKt.<> package com.adobe.marketing.mobile.util import com.adobe.marketing.mobile.Event import com.adobe.marketing.mobile.EventSource import com.adobe.marketing.mobile.EventType private const val KEY_EVENT_DATA_DEBUG = "debug" private const val KEY_DEBUG_EVENT_TYPE = "eventType" private const val KEY_DEBUG_EVENT_SOURCE = "eventSource" /** * The debug event type (identified by debug.eventType) from the event data if present, otherwise null */ val Event.debugEventType: String? get() = debugEventData?.get(KEY_DEBUG_EVENT_TYPE) as? String /** * The debug event source (identified by debug.eventSource) from the event data if present, otherwise null. */ val Event.debugEventSource: String? get() = debugEventData?.get(KEY_DEBUG_EVENT_SOURCE) as? String /** * Returns the debug event data (identified by data.debug) from the event if present, otherwise null. * @return the content of "debug" key within "Event.data" if present, * null if the event is not a debug event or if the debug data does not exist */ private val Event.debugEventData: Map<String, Any?>? get() { if (type != EventType.SYSTEM || source != EventSource.DEBUG) return null if (eventData == null) return null return DataReader.optTypedMap(Any::class.java, eventData, KEY_EVENT_DATA_DEBUG, null) ?: null }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/util/JSONUtils.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.util; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** Utility class for JSON objects. */ public final class JSONUtils { private JSONUtils() {} /** * Checks if the provided {@code JSONObject} is null or it has no element * * @param jsonObject the {@code JSONObject} to be verified * @return true if null or empty, false otherwise */ public static boolean isNullOrEmpty(@Nullable final JSONObject jsonObject) { return jsonObject == null || jsonObject.length() == 0; } /** * Checks if the provided {@code JSONArray} is null or it has no element * * @param jsonArray the {@code JSONArray} to be verified * @return true if null or empty, false otherwise */ public static boolean isNullOrEmpty(@Nullable final JSONArray jsonArray) { return jsonArray == null || jsonArray.length() == 0; } /** * Converts contents of a {@code JSONObject} into a {@code Map<String, Object>} * * @param jsonObject the {@code JSONObject} that is to be converted to Map * @return {@code Map<String, Object>} obtained after converting the {@code JSONObject} */ @Nullable public static Map<String, Object> toMap(@Nullable final JSONObject jsonObject) throws JSONException { if (jsonObject == null) { return null; } final Map<String, Object> map = new HashMap<>(); Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { final String key = keys.next(); map.put(key, fromJson(jsonObject.get(key))); } return map; } /** * Converts contents of a {@code JSONObject} into a {@code List<Object>} * * @param jsonArray the {@code JSONArray} that is to be converted to a List * @return {@code List<Object>} obtained after converting the {@code JSONObject} */ @Nullable public static List<Object> toList(@Nullable final JSONArray jsonArray) throws JSONException { if (jsonArray == null) { return null; } final List<Object> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { list.add(fromJson(jsonArray.get(i))); } return list; } private static Object fromJson(final Object json) throws JSONException { if (json == null || json == JSONObject.NULL) { return null; } else if (json instanceof JSONObject) { return toMap((JSONObject) json); } else if (json instanceof JSONArray) { return toList((JSONArray) json); } else { return json; } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/LaunchRulesConsequence.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine import com.adobe.marketing.mobile.Event import com.adobe.marketing.mobile.EventSource import com.adobe.marketing.mobile.EventType import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.LoggingMode import com.adobe.marketing.mobile.internal.eventhub.EventHub import com.adobe.marketing.mobile.internal.util.EventDataMerger import com.adobe.marketing.mobile.internal.util.prettify import com.adobe.marketing.mobile.rulesengine.DelimiterPair import com.adobe.marketing.mobile.rulesengine.Template import com.adobe.marketing.mobile.rulesengine.TokenFinder import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.util.EventDataUtils internal class LaunchRulesConsequence( private val extensionApi: ExtensionApi ) { private val logTag = "LaunchRulesConsequence" private var dispatchChainedEventsCount = mutableMapOf<String, Int>() companion object { private const val LAUNCH_RULE_TOKEN_LEFT_DELIMITER = "{%" private const val LAUNCH_RULE_TOKEN_RIGHT_DELIMITER = "%}" private const val CONSEQUENCE_TYPE_ADD = "add" private const val CONSEQUENCE_TYPE_MOD = "mod" private const val CONSEQUENCE_TYPE_DISPATCH = "dispatch" private const val CONSEQUENCE_DETAIL_ACTION_COPY = "copy" private const val CONSEQUENCE_DETAIL_ACTION_NEW = "new" // Do not process Dispatch consequence if chained event count is greater than max private const val MAX_CHAINED_CONSEQUENCE_COUNT = 1 private const val CONSEQUENCE_DISPATCH_EVENT_NAME = "Dispatch Consequence Result" private const val CONSEQUENCE_EVENT_DATA_KEY_ID = "id" private const val CONSEQUENCE_EVENT_DATA_KEY_TYPE = "type" private const val CONSEQUENCE_EVENT_DATA_KEY_DETAIL = "detail" private const val CONSEQUENCE_EVENT_DATA_KEY_CONSEQUENCE = "triggeredconsequence" private const val CONSEQUENCE_EVENT_NAME = "Rules Consequence Event" } /** * Processes the [matchedRules] against the supplied [event]. This evaluation may result * in dispatch of the supplied event after attachment, modification of its data or dispatch of * a new event from the supplied event * * @param event the event to be processed * @param matchedRules the rules against which the current events is to be processed * @return the token replaced [Event] after token replacement */ fun process(event: Event, matchedRules: List<LaunchRule>): Event { val dispatchChainCount = dispatchChainedEventsCount.remove(event.uniqueIdentifier) ?: 0 val launchTokenFinder = LaunchTokenFinder(event, extensionApi) var processedEvent: Event = event for (rule in matchedRules) { for (consequence in rule.consequenceList) { val consequenceWithConcreteValue = replaceToken(consequence, launchTokenFinder) when (consequenceWithConcreteValue.type) { CONSEQUENCE_TYPE_ADD -> { val attachedEventData = processAttachDataConsequence( consequenceWithConcreteValue, processedEvent.eventData ) ?: continue processedEvent = processedEvent.cloneWithEventData(attachedEventData) } CONSEQUENCE_TYPE_MOD -> { val modifiedEventData = processModifyDataConsequence( consequenceWithConcreteValue, processedEvent.eventData ) ?: continue processedEvent = processedEvent.cloneWithEventData(modifiedEventData) } CONSEQUENCE_TYPE_DISPATCH -> { if (dispatchChainCount >= MAX_CHAINED_CONSEQUENCE_COUNT) { Log.warning( LaunchRulesEngineConstants.LOG_TAG, logTag, "Unable to process dispatch consequence, max chained " + "dispatch consequences limit of $MAX_CHAINED_CONSEQUENCE_COUNT" + "met for this event uuid ${event.uniqueIdentifier}" ) continue } val dispatchEvent = processDispatchConsequence( consequenceWithConcreteValue, processedEvent ) ?: continue Log.trace( LaunchRulesEngineConstants.LOG_TAG, logTag, "processDispatchConsequence - Dispatching event - ${dispatchEvent.uniqueIdentifier}" ) extensionApi.dispatch(dispatchEvent) dispatchChainedEventsCount[dispatchEvent.uniqueIdentifier] = dispatchChainCount + 1 } else -> { val consequenceEvent = generateConsequenceEvent(consequenceWithConcreteValue, processedEvent) Log.trace( LaunchRulesEngineConstants.LOG_TAG, logTag, "evaluateRulesConsequence - Dispatching consequence event ${consequenceEvent.uniqueIdentifier}" ) extensionApi.dispatch(consequenceEvent) } } } } return processedEvent } /** * Evaluates the supplied event against the matched rules and returns the [RuleConsequence]'s * * @param event the event to be evaluated * @param matchedRules the rules whose consequences are to be processed * @return a token replaced list of [RuleConsequence]'s that match the supplied event. */ fun evaluate(event: Event, matchedRules: List<LaunchRule>): List<RuleConsequence> { val processedConsequences = mutableListOf<RuleConsequence>() val launchTokenFinder = LaunchTokenFinder(event, extensionApi) matchedRules.forEach { matchedRule -> matchedRule.consequenceList.forEach { consequence -> processedConsequences.add(replaceToken(consequence, launchTokenFinder)) } } return processedConsequences } /** * Replace tokens inside the provided [RuleConsequence] with the right value * * @param consequence [RuleConsequence] instance that may contain tokens * @param tokenFinder [TokenFinder] instance which replaces the tokens with values * @return the [RuleConsequence] with replaced tokens */ private fun replaceToken(consequence: RuleConsequence, tokenFinder: TokenFinder): RuleConsequence { val tokenReplacedMap = replaceToken(consequence.detail, tokenFinder) return RuleConsequence(consequence.id, consequence.type, tokenReplacedMap) } private fun replaceToken(value: Any?, tokenFinder: TokenFinder): Any? { return when (value) { is String -> replaceToken(value, tokenFinder) is Map<*, *> -> replaceToken(EventDataUtils.castFromGenericType(value), tokenFinder) is List<*> -> replaceToken(value, tokenFinder) else -> value } } private fun replaceToken(detail: Map<String, Any?>?, tokenFinder: TokenFinder): Map<String, Any?>? { if (detail.isNullOrEmpty()) { return null } val mutableDetail = detail.toMutableMap() for ((key, value) in detail) { mutableDetail[key] = replaceToken(value, tokenFinder) } return mutableDetail } private fun replaceToken(value: List<Any?>, tokenFinder: TokenFinder): List<Any?> { return value.map { replaceToken(it, tokenFinder) } } private fun replaceToken(value: String, tokenFinder: TokenFinder): String { val template = Template(value, DelimiterPair(LAUNCH_RULE_TOKEN_LEFT_DELIMITER, LAUNCH_RULE_TOKEN_RIGHT_DELIMITER)) return template.render(tokenFinder, LaunchRuleTransformer.createTransforming()) } /** * Process an attach data consequence event. Attaches the triggering event data from the [RuleConsequence] to the * triggering event data without overwriting the original event data. If either the event data * from the [RuleConsequence] or the triggering event data is null then the processing is aborted. * * @param consequence the [RuleConsequence] which contains the event data to attach * @param eventData the event data of the triggering [Event] * @return [Map] with the [RuleConsequence] data attached to the triggering event data, or * null if the processing fails */ private fun processAttachDataConsequence(consequence: RuleConsequence, eventData: Map<String, Any?>?): Map<String, Any?>? { val from = EventDataUtils.castFromGenericType(consequence.eventData) ?: run { Log.error( LaunchRulesEngineConstants.LOG_TAG, logTag, "Unable to process an AttachDataConsequence Event, 'eventData' is missing from 'details'" ) return null } val to = eventData ?: run { Log.error( LaunchRulesEngineConstants.LOG_TAG, logTag, "Unable to process an AttachDataConsequence Event, 'eventData' is missing from original event" ) return null } if (Log.getLogLevel() == LoggingMode.VERBOSE) { Log.trace( LaunchRulesEngineConstants.LOG_TAG, logTag, "Attaching event data with ${from.prettify()}" ) } return EventDataMerger.merge(from, to, false) } /** * Process a modify data consequence event. Modifies the triggering event data by merging the * event data from the [RuleConsequence] onto it. If either the event data * from the [RuleConsequence] or the triggering event data is null then the processing is aborted. * * @param consequence the [RuleConsequence] which contains the event data to attach * @param eventData the event data of the triggering [Event] * @return [Map] with the Event data modified with the [RuleConsequence] data, or * null if the processing fails */ private fun processModifyDataConsequence(consequence: RuleConsequence, eventData: Map<String, Any?>?): Map<String, Any?>? { val from = EventDataUtils.castFromGenericType(consequence.eventData) ?: run { Log.error( LaunchRulesEngineConstants.LOG_TAG, logTag, "Unable to process a ModifyDataConsequence Event, 'eventData' is missing from 'details'" ) return null } val to = eventData ?: run { Log.error( LaunchRulesEngineConstants.LOG_TAG, logTag, "Unable to process a ModifyDataConsequence Event, 'eventData' is missing from original event" ) return null } if (Log.getLogLevel() == LoggingMode.VERBOSE) { Log.trace( LaunchRulesEngineConstants.LOG_TAG, logTag, "Modifying event data with ${from.prettify()}" ) } return EventDataMerger.merge(from, to, true) } /** * Process a dispatch consequence event. Generates a new [Event] from the details contained within the [RuleConsequence] * * @param consequence the [RuleConsequence] which contains details on the new [Event] to generate * @param parentEvent the triggering Event for which a consequence is being generated * @return a new [Event] to be dispatched to the [EventHub], or null if the processing failed. */ private fun processDispatchConsequence(consequence: RuleConsequence, parentEvent: Event): Event? { val type = consequence.eventType ?: run { Log.error( LaunchRulesEngineConstants.LOG_TAG, logTag, "Unable to process a DispatchConsequence Event, 'type' is missing from 'details'" ) return null } val source = consequence.eventSource ?: run { Log.error( LaunchRulesEngineConstants.LOG_TAG, logTag, "Unable to process a DispatchConsequence Event, 'source' is missing from 'details'" ) return null } val action = consequence.eventDataAction ?: run { Log.error( LaunchRulesEngineConstants.LOG_TAG, logTag, "Unable to process a DispatchConsequence Event, 'eventdataaction' is missing from 'details'" ) return null } val dispatchEventData: Map<String, Any?>? when (action) { CONSEQUENCE_DETAIL_ACTION_COPY -> { dispatchEventData = parentEvent.eventData } CONSEQUENCE_DETAIL_ACTION_NEW -> { val data = EventDataUtils.castFromGenericType(consequence.eventData) dispatchEventData = data?.filterValues { it != null } } else -> { Log.error( LaunchRulesEngineConstants.LOG_TAG, logTag, "Unable to process a DispatchConsequence Event, unsupported 'eventdataaction', expected values copy/new" ) return null } } return Event.Builder(CONSEQUENCE_DISPATCH_EVENT_NAME, type, source) .setEventData(dispatchEventData) .chainToParentEvent(parentEvent) .build() } /** * Generate a consequence event with provided consequence data * @param consequence [RuleConsequence] of the rule * @param parentEvent the event for which the consequence is to be generated * @return a consequence [Event] */ private fun generateConsequenceEvent(consequence: RuleConsequence, parentEvent: Event): Event { val eventData = mutableMapOf<String, Any?>() eventData[CONSEQUENCE_EVENT_DATA_KEY_DETAIL] = consequence.detail eventData[CONSEQUENCE_EVENT_DATA_KEY_ID] = consequence.id eventData[CONSEQUENCE_EVENT_DATA_KEY_TYPE] = consequence.type return Event.Builder( CONSEQUENCE_EVENT_NAME, EventType.RULES_ENGINE, EventSource.RESPONSE_CONTENT ) .setEventData(mapOf(CONSEQUENCE_EVENT_DATA_KEY_CONSEQUENCE to eventData)) .chainToParentEvent(parentEvent) .build() } } // Extend RuleConsequence with helper methods for processing consequence events. private val RuleConsequence.eventData: Map<*, *>? get() = detail?.get("eventdata") as? Map<*, *> private val RuleConsequence.eventSource: String? get() = detail?.get("source") as? String private val RuleConsequence.eventType: String? get() = detail?.get("type") as? String private val RuleConsequence.eventDataAction: String? get() = detail?.get("eventdataaction") as? String
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/LaunchRulesEngine.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import com.adobe.marketing.mobile.Event; import com.adobe.marketing.mobile.EventSource; import com.adobe.marketing.mobile.EventType; import com.adobe.marketing.mobile.ExtensionApi; import com.adobe.marketing.mobile.rulesengine.ConditionEvaluator; import com.adobe.marketing.mobile.rulesengine.RulesEngine; import com.adobe.marketing.mobile.util.DataReader; import com.adobe.marketing.mobile.util.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LaunchRulesEngine { @VisibleForTesting static final String RULES_ENGINE_NAME = "name"; private final String name; private final RulesEngine<LaunchRule> ruleRulesEngine; private final ExtensionApi extensionApi; private final LaunchRulesConsequence launchRulesConsequence; private final List<Event> cachedEvents = new ArrayList<>(); private boolean initialRulesReceived = false; public LaunchRulesEngine(@NonNull final String name, @NonNull final ExtensionApi extensionApi) { this( name, extensionApi, new RulesEngine<>( new ConditionEvaluator(ConditionEvaluator.Option.CASE_INSENSITIVE), LaunchRuleTransformer.INSTANCE.createTransforming()), new LaunchRulesConsequence(extensionApi)); } @VisibleForTesting LaunchRulesEngine( final String name, final ExtensionApi extensionApi, final RulesEngine<LaunchRule> ruleEngine, final LaunchRulesConsequence launchRulesConsequence) { if (StringUtils.isNullOrEmpty(name)) { throw new IllegalArgumentException("LaunchRulesEngine cannot have a null/empty name"); } this.name = name; this.launchRulesConsequence = launchRulesConsequence; this.extensionApi = extensionApi; this.ruleRulesEngine = ruleEngine; } /** * Set a new set of rules, the new rules replace the current rules. * * @param rules a list of {@link LaunchRule}s */ public void replaceRules(final List<LaunchRule> rules) { if (rules == null) return; ruleRulesEngine.replaceRules(rules); // send a reset request event for the current LaunchRulesEngine final Event dispatchEvent = new Event.Builder(name, EventType.RULES_ENGINE, EventSource.REQUEST_RESET) .setEventData(Collections.singletonMap(RULES_ENGINE_NAME, name)) .build(); extensionApi.dispatch(dispatchEvent); } /** * Adds a new set of rules, the new rules are added to the current rules. * * @param rules a list of {@link LaunchRule}s */ public void addRules(final List<LaunchRule> rules) { ruleRulesEngine.addRules(rules); } /** * Processes the supplied event with all the rules that match it. This processing may result in * dispatch of the supplied event after attachment, modification of its data or dispatch of a * new event from the supplied event. * * @param event the event to be evaluated * @return the processed [Event] after token replacement. */ public Event processEvent(@NonNull final Event event) { if (event == null) { throw new IllegalArgumentException("Cannot evaluate null event."); } final List<LaunchRule> matchedRules = ruleRulesEngine.evaluate(new LaunchTokenFinder(event, extensionApi)); // if initial rule set has not been received, cache the event to be processed // when rules are set if (!initialRulesReceived) { handleCaching(event); } return launchRulesConsequence.process(event, matchedRules); } /** * Evaluates the supplied event against the all current rules and returns the {@link * RuleConsequence}'s from the rules that matched the supplied event. * * @param event the event to be evaluated * @return a {@code List<RuleConsequence>} that match the supplied event. */ public List<RuleConsequence> evaluateEvent(@NonNull final Event event) { if (event == null) { throw new IllegalArgumentException("Cannot evaluate null event."); } final List<LaunchRule> matchedRules = ruleRulesEngine.evaluate(new LaunchTokenFinder(event, extensionApi)); // get token replaced consequences return launchRulesConsequence.evaluate(event, matchedRules); } List<LaunchRule> getRules() { return ruleRulesEngine.getRules(); } @VisibleForTesting int getCachedEventCount() { return cachedEvents.size(); } private void reprocessCachedEvents() { for (Event cachedEvent : cachedEvents) { final List<LaunchRule> matchedRules = ruleRulesEngine.evaluate(new LaunchTokenFinder(cachedEvent, extensionApi)); launchRulesConsequence.process(cachedEvent, matchedRules); } // clear cached events and set the flag to indicate that rules were set at least once cachedEvents.clear(); initialRulesReceived = true; } private void handleCaching(final Event event) { // If this is an event to start processing of cachedEvents reprocess cached events // otherwise, add the event to cachedEvents till rules are set if (EventType.RULES_ENGINE.equals(event.getType()) && EventSource.REQUEST_RESET.equals(event.getSource()) && name.equals(DataReader.optString(event.getEventData(), RULES_ENGINE_NAME, ""))) { reprocessCachedEvents(); } else { cachedEvents.add(event); } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/RuleConsequence.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine /** * The data class representing a rule's consequence object * * @property id the consequence id * @property type the consequence type * @property detail the meta data of the consequence object * @constructor Constructs a new [RuleConsequence] */ data class RuleConsequence( val id: String, val type: String, val detail: Map<String, Any?>? )
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/LaunchRulesEngineConstants.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine internal object LaunchRulesEngineConstants { const val LOG_TAG = "LaunchRulesEngine" internal object Transform { const val URL_ENCODING_FUNCTION = "urlenc" const val TRANSFORM_TO_INT = "int" const val TRANSFORM_TO_DOUBLE = "double" const val TRANSFORM_TO_STRING = "string" const val TRANSFORM_TO_BOOL = "bool" } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/LaunchRuleTransformer.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine import com.adobe.marketing.mobile.internal.util.UrlEncoder import com.adobe.marketing.mobile.rulesengine.Transformer import com.adobe.marketing.mobile.rulesengine.TransformerBlock import com.adobe.marketing.mobile.rulesengine.Transforming internal object LaunchRuleTransformer { /** * Generates the [Transforming] instance used by Launch Rules Engine. * * @return instance of [Transforming] **/ fun createTransforming(): Transforming { val transformer = Transformer() addConsequenceTransform(transformer) addTypeTransform(transformer) return transformer } /** * Registers a [TransformerBlock] for [LaunchRulesEngineConstants.Transform.URL_ENCODING_FUNCTION] * to encode a `String` value to url format. * * @param[transformer] [Transformer] instance used to register the [TransformerBlock] */ private fun addConsequenceTransform(transformer: Transformer) { transformer.register(LaunchRulesEngineConstants.Transform.URL_ENCODING_FUNCTION) { value -> if (value is String) { UrlEncoder.urlEncode(value) } else { value } } } /** * Registers multiple [TransformerBlock] to transform a value into one of * [LaunchRulesEngineConstants.Transform] types. * * @param[transformer] [Transformer] instance used to register the [TransformerBlock] */ private fun addTypeTransform(transformer: Transformer) { transformer.register(LaunchRulesEngineConstants.Transform.TRANSFORM_TO_INT) { value -> when (value) { is String -> value.toIntOrNull() ?: value is Number -> value.toInt() is Boolean -> if (value) 1 else 0 else -> value } } transformer.register(LaunchRulesEngineConstants.Transform.TRANSFORM_TO_STRING) { value -> value?.toString() } transformer.register(LaunchRulesEngineConstants.Transform.TRANSFORM_TO_DOUBLE) { value -> when (value) { is String -> value.toDoubleOrNull() ?: value is Number -> value.toDouble() is Boolean -> if (value) 1.0 else 0.0 else -> value } } transformer.register(LaunchRulesEngineConstants.Transform.TRANSFORM_TO_BOOL) { value -> when (value) { is String -> java.lang.Boolean.parseBoolean(value) is Number -> (value.toLong() == 1L && value.toDouble() == 1.0) else -> value } } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/HistoricalEventsQuerying.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine import com.adobe.marketing.mobile.EventHistoryRequest import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.services.Log import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit private const val LOG_TAG = "historicalEventsQuerying" private const val SEARCH_TYPE_ORDERED = "ordered" private const val ASYNC_TIMEOUT = 1000L @JvmSynthetic internal fun historicalEventsQuerying( requests: List<EventHistoryRequest>, searchType: String, extensionApi: ExtensionApi ): Int { return try { val latch = CountDownLatch(1) var eventCounts = 0 extensionApi.getHistoricalEvents( requests.toTypedArray(), searchType == SEARCH_TYPE_ORDERED ) { eventCounts = it latch.countDown() } latch.await(ASYNC_TIMEOUT, TimeUnit.MILLISECONDS) eventCounts } catch (e: Exception) { Log.warning( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Unable to retrieve historical events, caused by the exception: ${e.localizedMessage}" ) 0 } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/LaunchTokenFinder.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine import com.adobe.marketing.mobile.Event import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.MobileCore import com.adobe.marketing.mobile.SharedStateResolution import com.adobe.marketing.mobile.internal.util.flattening import com.adobe.marketing.mobile.internal.util.serializeToQueryString import com.adobe.marketing.mobile.rulesengine.TokenFinder import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.util.TimeUtils import org.json.JSONObject import java.security.SecureRandom internal class LaunchTokenFinder(val event: Event, val extensionApi: ExtensionApi) : TokenFinder { companion object { private const val LOG_TAG = "LaunchTokenFinder" private const val KEY_EVENT_TYPE = "~type" private const val KEY_EVENT_SOURCE = "~source" private const val KEY_TIMESTAMP_UNIX = "~timestampu" private const val KEY_TIMESTAMP_ISO8601 = "~timestampz" private const val KEY_TIMESTAMP_PLATFORM = "~timestampp" private const val KEY_SDK_VERSION = "~sdkver" private const val KEY_CACHEBUST = "~cachebust" private const val KEY_ALL_URL = "~all_url" private const val KEY_ALL_JSON = "~all_json" private const val KEY_SHARED_STATE = "~state." private const val EMPTY_STRING = "" private const val RANDOM_INT_BOUNDARY = 100000000 private const val SHARED_STATE_KEY_DELIMITER = "/" } // ======================================================== // public methods // ======================================================== /** * Returns the value for the [key] provided as input. * * * If the `key` is a special key recognized by SDK, the value is determined based on incoming `Event`, * or `EventHub#moduleSharedStates` data. Otherwise the key is searched in the current `Event`'s data * and the corresponding value is returned. * * @param key [String] containing the key whose value needs to be determined * * @return [Any] containing value to be substituted for the [key], null if the key does not exist */ override fun get(key: String): Any? { return when (key.trim()) { EMPTY_STRING -> null KEY_EVENT_TYPE -> event.type KEY_EVENT_SOURCE -> event.source KEY_TIMESTAMP_UNIX -> TimeUtils.getUnixTimeInSeconds().toString() KEY_TIMESTAMP_ISO8601 -> TimeUtils.getISO8601DateNoColon() KEY_TIMESTAMP_PLATFORM -> TimeUtils.getISO8601UTCDateWithMilliseconds() KEY_SDK_VERSION -> MobileCore.extensionVersion() KEY_CACHEBUST -> SecureRandom().nextInt(RANDOM_INT_BOUNDARY).toString() KEY_ALL_URL -> { if (event.eventData == null) { Log.debug( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Triggering event ${event.uniqueIdentifier} - Event data is null, can not use it to generate an url query string" ) return EMPTY_STRING } val eventDataAsObjectMap = event.eventData.flattening() eventDataAsObjectMap.serializeToQueryString() } KEY_ALL_JSON -> { if (event.eventData == null) { Log.debug( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Triggering event ${event.uniqueIdentifier} - Event data is null, can not use it to generate a json string" ) return EMPTY_STRING } try { JSONObject(event.eventData).toString() } catch (e: Exception) { Log.debug( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Triggering event ${event.uniqueIdentifier} - Failed to generate a json string ${e.message}" ) return EMPTY_STRING } } else -> { if (key.startsWith(KEY_SHARED_STATE)) { getValueFromSharedState(key) } else { getValueFromEvent(key) } } } } // ======================================================== // private getter methods // ======================================================== private fun getValueFromSharedState(key: String): Any? { val sharedStateKeyString = key.substring(KEY_SHARED_STATE.length) if (sharedStateKeyString.isBlank()) { return null } if (!sharedStateKeyString.contains(SHARED_STATE_KEY_DELIMITER)) { return null } val (sharedStateName, dataKeyName) = sharedStateKeyString.split(SHARED_STATE_KEY_DELIMITER) val sharedStateMap = extensionApi.getSharedState( sharedStateName, event, false, SharedStateResolution.ANY )?.value?.flattening() if (sharedStateMap.isNullOrEmpty() || dataKeyName.isBlank() || !sharedStateMap.containsKey(dataKeyName)) { return null } return sharedStateMap[dataKeyName] } /** * Returns the value for the [key] provided as input by searching in the current [Event]'s data. * * @param key [String] containing the key whose value needs to be determined * * @return [Any] containing value to be substituted for the [key] from the [Event]'s data if [key] is present, null otherwise */ private fun getValueFromEvent(key: String): Any? { if (event.eventData == null) { return EMPTY_STRING } val eventDataMap = event.eventData.flattening() return eventDataMap[key] } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/LaunchRule.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine import com.adobe.marketing.mobile.rulesengine.Evaluable import com.adobe.marketing.mobile.rulesengine.Rule /** * The data class representing the given [Evaluable] and a list of [RuleConsequence] objects. * * @property condition an object of [Evaluable] * @property consequenceList a list of [RuleConsequence] objects * @constructor Constructs a new [LaunchRule] */ data class LaunchRule(val condition: Evaluable, val consequenceList: List<RuleConsequence>) : Rule { override fun getEvaluable(): Evaluable { return condition } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/json/JSONCondition.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.json import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.launch.rulesengine.LaunchRulesEngineConstants import com.adobe.marketing.mobile.rulesengine.Evaluable import com.adobe.marketing.mobile.services.Log import org.json.JSONObject /** * The class representing a Rule's condition * * @constructor Constructs a new [JSONCondition] */ internal abstract class JSONCondition { companion object { private const val LOG_TAG = "JSONCondition" private const val KEY_TYPE = "type" private const val KEY_DEFINITION = "definition" private const val TYPE_VALUE_GROUP = "group" private const val TYPE_VALUE_MATCHER = "matcher" private const val TYPE_VALUE_HISTORICAL = "historical" /** * Build a subclass of [JSONCondition] * * @param jsonCondition a JSON object of a Rule's condition * @return a subclass of [JSONCondition] */ @JvmSynthetic internal fun build(jsonCondition: JSONObject?, extensionApi: ExtensionApi): JSONCondition? { if (jsonCondition !is JSONObject) return null return try { when (val type = jsonCondition.getString(KEY_TYPE)) { TYPE_VALUE_GROUP -> GroupCondition( JSONDefinition.buildDefinitionFromJSON( jsonCondition.getJSONObject( KEY_DEFINITION ), extensionApi ) ) TYPE_VALUE_MATCHER -> MatcherCondition( JSONDefinition.buildDefinitionFromJSON( jsonCondition.getJSONObject( KEY_DEFINITION ), extensionApi ) ) TYPE_VALUE_HISTORICAL -> HistoricalCondition( JSONDefinition.buildDefinitionFromJSON( jsonCondition.getJSONObject( KEY_DEFINITION ), extensionApi ), extensionApi ) else -> { Log.error( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Unsupported condition type - $type" ) null } } } catch (e: Exception) { Log.error( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Failed to parse [rule.condition] JSON, the error is: ${e.message}" ) null } } } /** * Converts itself to a [Evaluable] * * @return an optional [Evaluable] */ @JvmSynthetic abstract fun toEvaluable(): Evaluable? }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/json/JSONRule.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.json import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.internal.util.map import com.adobe.marketing.mobile.launch.rulesengine.LaunchRule import com.adobe.marketing.mobile.launch.rulesengine.LaunchRulesEngineConstants import com.adobe.marketing.mobile.rulesengine.Evaluable import com.adobe.marketing.mobile.services.Log import org.json.JSONArray import org.json.JSONObject /** * The class representing a Rule */ internal class JSONRule private constructor( val condition: JSONObject, val consequences: JSONArray ) { companion object { private const val LOG_TAG = "JSONRule" private const val KEY_CONDITION = "condition" private const val KEY_CONSEQUENCES = "consequences" /** * Optionally constructs a new [JSONRule] * * @param jsonObject a [JSONObject] of the Rule * @return a new [JSONRule] or null */ operator fun invoke(jsonObject: JSONObject?): JSONRule? { if (jsonObject !is JSONObject) return null val condition = jsonObject.getJSONObject(KEY_CONDITION) val consequences = jsonObject.getJSONArray(KEY_CONSEQUENCES) if (condition !is JSONObject || consequences !is JSONArray) { Log.error( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Failed to extract [rule.condition] or [rule.consequences]." ) return null } return JSONRule(condition, consequences) } } /** * Converts itself to a [LaunchRule] * * @return an object of [LaunchRule] */ @JvmSynthetic internal fun toLaunchRule(extensionApi: ExtensionApi): LaunchRule? { val evaluable = JSONCondition.build(condition, extensionApi)?.toEvaluable() if (evaluable !is Evaluable) { Log.error( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Failed to build LaunchRule from JSON, the [rule.condition] can't be parsed to Evaluable." ) return null } val consequenceList = consequences.map { JSONConsequence(it as? JSONObject)?.toRuleConsequence() ?: throw Exception() } return LaunchRule(evaluable, consequenceList) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/json/JSONDefinition.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.json import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.internal.util.map import com.adobe.marketing.mobile.internal.util.toMap import org.json.JSONArray import org.json.JSONException import org.json.JSONObject /** * The class representing a Rule condition's definition * * @property logic the `logic` filed of the JSON object * @property conditions the `conditions` filed of the JSON object * @property key the `key` filed of the JSON object * @property matcher the `matcher` filed of the JSON object * @property values the `values` filed of the JSON object * @property events the `events` filed of the JSON object * @property value the `value` filed of the JSON object * @property from the `from` filed of the JSON object * @property to the `to` filed of the JSON object * @property searchType the `searchType` filed of the JSON object * @constructor Constructs a new [JSONDefinition] */ internal data class JSONDefinition( val logic: String?, val conditions: List<JSONCondition>?, val key: String?, val matcher: String?, val values: List<Any?>?, val events: List<Map<String, Any?>>?, val value: Any?, val from: Long?, val to: Long?, val searchType: String? ) { companion object { private const val DEFINITION_KEY_LOGIC = "logic" private const val DEFINITION_KEY_CONDITIONS = "conditions" private const val DEFINITION_KEY_KEY = "key" private const val DEFINITION_KEY_MATCHER = "matcher" private const val DEFINITION_KEY_VALUES = "values" private const val DEFINITION_KEY_EVENTS = "events" private const val DEFINITION_KEY_VALUE = "value" private const val DEFINITION_KEY_FROM = "from" private const val DEFINITION_KEY_TO = "to" private const val DEFINITION_KEY_SEARCH_TYPE = "searchType" /** * Builds a new [JSONDefinition] * * @param jsonObject a [JSONObject] of a Rule condition's definition * @return a new [JSONDefinition] */ @JvmSynthetic internal fun buildDefinitionFromJSON( jsonObject: JSONObject, extensionApi: ExtensionApi ): JSONDefinition { val logic = jsonObject.opt(DEFINITION_KEY_LOGIC) as? String val conditions = buildConditionList(jsonObject.optJSONArray(DEFINITION_KEY_CONDITIONS), extensionApi) val key = jsonObject.opt(DEFINITION_KEY_KEY) as? String val matcher = jsonObject.opt(DEFINITION_KEY_MATCHER) as? String val values = buildValueList(jsonObject.optJSONArray(DEFINITION_KEY_VALUES)) val events = buildValueMapList(jsonObject.optJSONArray(DEFINITION_KEY_EVENTS)) val value = jsonObject.opt(DEFINITION_KEY_VALUE) val from = jsonObject.opt(DEFINITION_KEY_FROM) as? Long val to = jsonObject.opt(DEFINITION_KEY_TO) as? Long val searchType = jsonObject.opt(DEFINITION_KEY_SEARCH_TYPE) as? String return JSONDefinition( logic, conditions, key, matcher, values, events, value, from, to, searchType ) } private fun buildConditionList( jsonArray: JSONArray?, extensionApi: ExtensionApi ): List<JSONCondition>? { return jsonArray?.map { JSONCondition.build(it as? JSONObject, extensionApi) ?: throw JSONException("Unsupported [rule.condition] JSON format: $it ") } } private fun buildValueList(jsonArray: JSONArray?): List<Any?>? { return jsonArray?.map { it } } private fun buildValueMapList(jsonArray: JSONArray?): List<Map<String, Any?>>? { return jsonArray?.map { (it as? JSONObject)?.toMap() ?: throw JSONException("Unsupported [rule.condition.historical.events] JSON format: $it ") } } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/json/JSONConsequence.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.json import com.adobe.marketing.mobile.internal.util.toMap import com.adobe.marketing.mobile.launch.rulesengine.RuleConsequence import org.json.JSONObject /** * The class representing a Rule's consequence */ internal class JSONConsequence private constructor( private val id: String, private val type: String, private val detail: Map<String, Any?>? ) { companion object { private const val KEY_ID = "id" private const val KEY_TYPE = "type" private const val KEY_DETAIL = "detail" operator fun invoke(jsonObject: JSONObject?): JSONConsequence? { if (jsonObject !is JSONObject) return null return JSONConsequence( jsonObject.optString(KEY_ID), jsonObject.optString(KEY_TYPE), jsonObject.optJSONObject(KEY_DETAIL)?.toMap() ) } } /** * Converts itself to a [RuleConsequence] object * * @return an object of [RuleConsequence] */ @JvmSynthetic internal fun toRuleConsequence(): RuleConsequence { return RuleConsequence(this.id, this.type, this.detail) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/json/HistoricalCondition.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.json import com.adobe.marketing.mobile.EventHistoryRequest import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.launch.rulesengine.LaunchRulesEngineConstants import com.adobe.marketing.mobile.launch.rulesengine.historicalEventsQuerying import com.adobe.marketing.mobile.rulesengine.ComparisonExpression import com.adobe.marketing.mobile.rulesengine.Evaluable import com.adobe.marketing.mobile.rulesengine.OperandFunction import com.adobe.marketing.mobile.rulesengine.OperandLiteral import com.adobe.marketing.mobile.services.Log internal class HistoricalCondition( private val definition: JSONDefinition, private val extensionApi: ExtensionApi ) : JSONCondition() { companion object { private const val LOG_TAG = "HistoricalCondition" } override fun toEvaluable(): Evaluable? { val valueAsInt = definition.value val operationName = MatcherCondition.MATCHER_MAPPING[definition.matcher] if (definition.events !is List<*> || operationName !is String || valueAsInt !is Int ) { Log.error( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Failed to build Evaluable from definition JSON: \n $definition" ) return null } val fromDate = definition.from ?: 0 val toDate = definition.to ?: 0 val searchType = definition.searchType ?: "any" val requestEvents = definition.events.map { EventHistoryRequest(it, fromDate, toDate) } return ComparisonExpression( OperandFunction( { try { @Suppress("UNCHECKED_CAST") historicalEventsQuerying( it[0] as List<EventHistoryRequest>, it[1] as String, extensionApi ) } catch (e: Exception) { 0 } }, requestEvents, searchType ), operationName, OperandLiteral(valueAsInt) ) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/json/JSONRuleRoot.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.json import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.internal.util.map import com.adobe.marketing.mobile.launch.rulesengine.LaunchRule import com.adobe.marketing.mobile.launch.rulesengine.LaunchRulesEngineConstants import com.adobe.marketing.mobile.services.Log import org.json.JSONArray import org.json.JSONObject /** * The class representing a set of Rules */ internal class JSONRuleRoot private constructor(val version: String, val jsonArray: JSONArray) { companion object { private const val LOG_TAG = "JSONRuleRoot" private const val KEY_VERSION = "version" private const val KEY_RULES = "rules" operator fun invoke(jsonObject: JSONObject): JSONRuleRoot? { val version = jsonObject.optString(KEY_VERSION, "0") val rules = jsonObject.optJSONArray(KEY_RULES) if (rules !is JSONArray) { Log.error( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Failed to extract [launch_json.rules]" ) return null } return JSONRuleRoot(version, rules) } } /** * Converts itself to a list of [LaunchRule]s * * @return a list of [LaunchRule]s */ @JvmSynthetic fun toLaunchRules(extensionApi: ExtensionApi): List<LaunchRule> { return jsonArray.map { JSONRule(it as? JSONObject)?.toLaunchRule(extensionApi) ?: throw Exception() } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/json/JSONRulesParser.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.json import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.launch.rulesengine.LaunchRule import com.adobe.marketing.mobile.launch.rulesengine.LaunchRulesEngineConstants import com.adobe.marketing.mobile.services.Log import org.json.JSONObject import org.json.JSONTokener /** * Parses the JSON string to a list of [LaunchRule]s */ object JSONRulesParser { private const val LOG_TAG = "JSONRulesParser" /** * Parses a set of JSON rules to a list of [LaunchRule]s * * @param jsonString a JSON string * @return a list of [LaunchRule]s */ @JvmStatic fun parse(jsonString: String, extensionApi: ExtensionApi): List<LaunchRule>? { try { val jsonObject = JSONTokener(jsonString).nextValue() if (jsonObject is JSONObject) { return JSONRuleRoot(jsonObject)?.toLaunchRules(extensionApi) } } catch (e: Exception) { Log.error( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Failed to parse launch rules JSON: \n $jsonString" ) } return null } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/json/GroupCondition.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.json import com.adobe.marketing.mobile.launch.rulesengine.LaunchRulesEngineConstants import com.adobe.marketing.mobile.rulesengine.Evaluable import com.adobe.marketing.mobile.rulesengine.LogicalExpression import com.adobe.marketing.mobile.services.Log import java.util.Locale /** * The class representing a group of [JSONCondition]s */ internal class GroupCondition(private val definition: JSONDefinition) : JSONCondition() { companion object { private const val LOG_TAG = "GroupCondition" private val LOGICAL_OPERATORS = listOf("or", "and") } @JvmSynthetic override fun toEvaluable(): Evaluable? { if (definition.logic !is String || definition.conditions !is List<*> || definition.conditions.isEmpty()) { return null } val logicalOperator = definition.logic.lowercase(Locale.ROOT) if (logicalOperator !in LOGICAL_OPERATORS) { Log.error( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Unsupported logical operator: $logicalOperator" ) return null } val evaluableList = definition.conditions.map { it.toEvaluable() } return LogicalExpression(evaluableList, logicalOperator) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/json/MatcherCondition.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.json import com.adobe.marketing.mobile.launch.rulesengine.LaunchRulesEngineConstants import com.adobe.marketing.mobile.rulesengine.ComparisonExpression import com.adobe.marketing.mobile.rulesengine.Evaluable import com.adobe.marketing.mobile.rulesengine.LogicalExpression import com.adobe.marketing.mobile.rulesengine.OperandLiteral import com.adobe.marketing.mobile.rulesengine.OperandMustacheToken import com.adobe.marketing.mobile.rulesengine.UnaryExpression import com.adobe.marketing.mobile.services.Log /** * The class representing a matcher condition */ internal class MatcherCondition(private val definition: JSONDefinition) : JSONCondition() { companion object { private const val LOG_TAG = "MatcherCondition" private const val OPERATION_NAME_OR = "or" internal val MATCHER_MAPPING = mapOf( "eq" to "equals", "ne" to "notEquals", "gt" to "greaterThan", "ge" to "greaterEqual", "lt" to "lessThan", "le" to "lessEqual", "co" to "contains", "nc" to "notContains", "sw" to "startsWith", "ew" to "endsWith", "ex" to "exists", "nx" to "notExist" ) } @JvmSynthetic override fun toEvaluable(): Evaluable? { if (definition.matcher !is String || definition.key !is String) { Log.error( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "[key] or [matcher] is not String, failed to build Evaluable from definition JSON: \n $definition" ) return null } val values: List<Any?> = definition.values ?: listOf() return when (values.size) { 0 -> convert(definition.key, definition.matcher, null) 1 -> convert(definition.key, definition.matcher, values[0]) in 2..Int.MAX_VALUE -> { val operands = values.map { convert(definition.key, definition.matcher, it) } if (operands.isEmpty()) null else LogicalExpression(operands, OPERATION_NAME_OR) } else -> null } } private fun convert(key: String, matcher: String, value: Any?): Evaluable? { val operationName = MATCHER_MAPPING[matcher] if (operationName == null) { Log.error( LaunchRulesEngineConstants.LOG_TAG, LOG_TAG, "Failed to build Evaluable from [type:matcher] json, [definition.matcher = $matcher] is not supported." ) return null } if (value == null) { return UnaryExpression( OperandMustacheToken("{{$key}}", Any::class.java as Class<*>), operationName ) } val (javaClass: Any, token: String) = when (value) { is String -> Pair( String::class.java, "{{${LaunchRulesEngineConstants.Transform.TRANSFORM_TO_STRING}($key)}}" ) is Int -> Pair( Number::class.java, "{{${LaunchRulesEngineConstants.Transform.TRANSFORM_TO_INT}($key)}}" ) is Double -> Pair( Number::class.java, "{{${LaunchRulesEngineConstants.Transform.TRANSFORM_TO_DOUBLE}($key)}}" ) // note: Kotlin.Boolean is not mapped to java.lang.Boolean correctly is Boolean -> Pair( java.lang.Boolean::class.java, "{{${LaunchRulesEngineConstants.Transform.TRANSFORM_TO_BOOL}($key)}}" ) is Float -> Pair( Number::class.java, "{{${LaunchRulesEngineConstants.Transform.TRANSFORM_TO_DOUBLE}($key)}}" ) else -> Pair(Any::class.java, "{{$key}}") } return ComparisonExpression( OperandMustacheToken(token, javaClass as Class<*>), operationName, OperandLiteral(value) ) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/download/RulesLoadResult.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.download; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** A holder for the data and result returned by {@code RulesLoader} when loading rules. */ public class RulesLoadResult { private final String data; private final Reason reason; /** Represents the reason why the downloaded data is returned as such */ public enum Reason { /** The requested download source is invalid. Example: Invalid url, non-existent asset */ INVALID_SOURCE, /** Extraction of the rules zip file failed. */ ZIP_EXTRACTION_FAILED, /** Content cannot be written into the cache directory used by {@code RulesLoader} */ CANNOT_CREATE_TEMP_DIR, /** Content cannot be written into a temp directory used by {@code RulesLoader} */ CANNOT_STORE_IN_TEMP_DIR, /** Requested content has not been modified at source. */ NOT_MODIFIED, /** The requested rules were not found. */ NO_DATA, SUCCESS, } public RulesLoadResult(@Nullable final String data, @NonNull final Reason reason) { this.data = data; this.reason = reason; } @Nullable public String getData() { return data; } @NonNull public Reason getReason() { return reason; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/download/RulesZipProcessingHelper.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.download; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import com.adobe.marketing.mobile.internal.CoreConstants; import com.adobe.marketing.mobile.internal.util.FileUtils; import com.adobe.marketing.mobile.internal.util.StringEncoder; import com.adobe.marketing.mobile.services.Log; import com.adobe.marketing.mobile.services.ServiceProvider; import com.adobe.marketing.mobile.util.StreamUtils; import com.adobe.marketing.mobile.util.StringUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** Helper class to handle rules zip file related processing. */ class RulesZipProcessingHelper { private static final String TAG = "RulesZipProcessingHelper"; @VisibleForTesting static final String TEMP_DOWNLOAD_DIR = "aepsdktmp"; private static final String TEMP_RULES_ZIP = "rules.zip"; private static final String TEMP_RULES_JSON = "rules.json"; /** * Creates a temporary directory to store and process rules. Such a directory (if created * successfully) is accessible for operations in this class via {@code tag}. * * @param tag the tag which can be used later to perform operations on the content stored in the * directory. * @return true if the directory creation is successful; false otherwise. */ boolean createTemporaryRulesDirectory(final String tag) { if (!canProcess(tag)) return false; final File tempExtractDir = getTemporaryDirectory(tag); if (!tempExtractDir.exists() && !tempExtractDir.mkdirs()) { Log.debug( CoreConstants.LOG_TAG, TAG, "Cannot access application cache directory to create temp dir."); return false; } return true; } /** * Stores the content read from the stream {@code zip} into the folder created via {@code * createTemporaryRulesDirectory(tag)} previously created * * @param tag tag for the folder into which the input stream should be stored into * @param zip the rules zip stream that is to be stored * @return true if the zip stream was successfully copied; false otherwise. */ boolean storeRulesInTemporaryDirectory(final String tag, final InputStream zip) { if (!canProcess(tag)) return false; final boolean fileRead = FileUtils.readInputStreamIntoFile(getZipFileHandle(tag), zip, false); if (!fileRead) { Log.debug(CoreConstants.LOG_TAG, TAG, "Cannot read response content into temp dir."); return false; } return true; } /** * Extracts the rules.zip present in the directory created via {@code * createTemporaryRulesDirectory(tag)} and attempts to find and read the content of file with * name TEMP_RULES_JSON from that directory. * * @param tag the tag used when creating and storing contents into the temporary directory. * @return the contents of TEMP_RULES_JSON if it was found and was readable; null otherwise. */ String unzipRules(final String tag) { if (!canProcess(tag)) return null; final File temporaryDirectory = getTemporaryDirectory(tag); final boolean extracted = FileUtils.extractFromZip(getZipFileHandle(tag), temporaryDirectory.getPath()); if (!extracted) { Log.debug( CoreConstants.LOG_TAG, TAG, "Failed to extract rules response zip into temp dir."); return null; } final File extractedRulesJsonFile = new File(temporaryDirectory.getPath() + File.separator + TEMP_RULES_JSON); if (!extractedRulesJsonFile.exists()) { Log.debug( CoreConstants.LOG_TAG, TAG, "Extract rules directory does not contain a rules.json file."); return null; } try (final FileInputStream fileInputStream = new FileInputStream(extractedRulesJsonFile)) { final String rules = StreamUtils.readAsString(fileInputStream); if (rules == null) { Log.debug(CoreConstants.LOG_TAG, TAG, "Null content from rules.json file."); return null; } return rules; } catch (final IOException e) { Log.debug( CoreConstants.LOG_TAG, TAG, "Exception while processing rules from source %s", tag); return null; } } /** * Deletes the temporary directory created via {@code createTemporaryRulesDirectory()} * * @param tag the tag used to create that */ void deleteTemporaryDirectory(final String tag) { if (!canProcess(tag)) return; FileUtils.deleteFile(getTemporaryDirectory(tag), true); } @VisibleForTesting File getTemporaryDirectory(@NonNull final String tag) { final String hash = StringEncoder.sha2hash(tag); return new File( ServiceProvider.getInstance() .getDeviceInfoService() .getApplicationCacheDir() .getPath() + File.separator + TEMP_DOWNLOAD_DIR + File.separator + hash); } private File getZipFileHandle(@NonNull final String tag) { return new File(getTemporaryDirectory(tag).getPath() + File.separator + TEMP_RULES_ZIP); } private boolean canProcess(@NonNull final String tag) { return !StringUtils.isNullOrEmpty(tag); } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/launch/rulesengine/download/RulesLoader.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.launch.rulesengine.download; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import com.adobe.marketing.mobile.AdobeCallback; import com.adobe.marketing.mobile.services.HttpConnecting; import com.adobe.marketing.mobile.services.HttpMethod; import com.adobe.marketing.mobile.services.Log; import com.adobe.marketing.mobile.services.NetworkCallback; import com.adobe.marketing.mobile.services.NetworkRequest; import com.adobe.marketing.mobile.services.ServiceProvider; import com.adobe.marketing.mobile.services.caching.CacheEntry; import com.adobe.marketing.mobile.services.caching.CacheExpiry; import com.adobe.marketing.mobile.services.caching.CacheResult; import com.adobe.marketing.mobile.util.StreamUtils; import com.adobe.marketing.mobile.util.StringUtils; import com.adobe.marketing.mobile.util.TimeUtils; import com.adobe.marketing.mobile.util.UrlUtils; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; /** * Facilitates the download and caching of rules from a url as well as an asset bundled with the * app. */ public class RulesLoader { private static final String TAG = "RulesLoader"; private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 10000; private static final int DEFAULT_READ_TIMEOUT_MS = 10000; static final String HTTP_HEADER_IF_MODIFIED_SINCE = "If-Modified-Since"; static final String HTTP_HEADER_IF_NONE_MATCH = "If-None-Match"; static final String HTTP_HEADER_LAST_MODIFIED = "Last-Modified"; static final String HTTP_HEADER_ETAG = "ETag"; /** The cache name used for storing the downloaded results. */ private final String cacheName; private final RulesZipProcessingHelper rulesZipProcessingHelper; public RulesLoader(@NonNull final String cacheName) { this(cacheName, new RulesZipProcessingHelper()); } @VisibleForTesting RulesLoader( @NonNull final String cacheName, @NonNull final RulesZipProcessingHelper rulesZipProcessingHelper) { if (StringUtils.isNullOrEmpty(cacheName)) throw new IllegalArgumentException("Name cannot be null or empty"); this.cacheName = cacheName; this.rulesZipProcessingHelper = rulesZipProcessingHelper; } /** * Loads rules from the {@code url} and invokes {@code callback} with the extracted rules. * Additionally, the extracted content is cached in cache bucket with name {@code name} and * {@code url} as the key in {@code CacheService}. * * @param url the url from which the compressed rules are to be downloaded * @param callback the callback that will be invoked with the result of the download */ public void loadFromUrl( @NonNull final String url, @NonNull final AdobeCallback<RulesLoadResult> callback) { if (!UrlUtils.isValidUrl(url)) { Log.trace(TAG, cacheName, "Provided download url: %s is null or empty. ", url); callback.call(new RulesLoadResult(null, RulesLoadResult.Reason.INVALID_SOURCE)); return; } final CacheResult cacheResult = ServiceProvider.getInstance().getCacheService().get(cacheName, url); final NetworkRequest networkRequest = new NetworkRequest( url, HttpMethod.GET, null, extractHeadersFromCache(cacheResult), DEFAULT_CONNECTION_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS); final NetworkCallback networkCallback = response -> { final RulesLoadResult result = handleDownloadResponse(url, response); if (response != null) { response.close(); } callback.call(result); }; ServiceProvider.getInstance() .getNetworkService() .connectAsync(networkRequest, networkCallback); } /** * Loads rules from an asset bundled with the app and returns the extracted rules. Additionally, * the extracted content is cached in cache bucket with name {@code RulesLoader.getCacheName()} * and {@code assetName} as the key in {@code CacheService}. * * @param assetName the asset name from where the rules must be fetched * @return {@code RulesDownloadResult} indicating the result of the load operation. */ @NonNull public RulesLoadResult loadFromAsset(@NonNull final String assetName) { if (StringUtils.isNullOrEmpty(assetName)) { new RulesLoadResult(null, RulesLoadResult.Reason.INVALID_SOURCE); } final InputStream bundledRulesStream = ServiceProvider.getInstance().getDeviceInfoService().getAsset(assetName); if (bundledRulesStream == null) { Log.trace(TAG, cacheName, "Provided asset: %s is invalid.", assetName); return new RulesLoadResult(null, RulesLoadResult.Reason.INVALID_SOURCE); } return extractRules(assetName, bundledRulesStream, new HashMap<>()); } /** * Loads rules that were previously cached via {@code loadFromAsset()} or {@code loadFromUrl} * * @param key the asset name or url that was previously used for loading and storing rules via * {@code loadFromAsset()} or {@code loadFromUrl} * @return {@code RulesDownloadResult} indicating the result of the load operation. */ @NonNull public RulesLoadResult loadFromCache(@NonNull final String key) { if (StringUtils.isNullOrEmpty(key)) { return new RulesLoadResult(null, RulesLoadResult.Reason.INVALID_SOURCE); } final CacheResult cacheResult = ServiceProvider.getInstance().getCacheService().get(cacheName, key); if (cacheResult == null) { return new RulesLoadResult(null, RulesLoadResult.Reason.NO_DATA); } return new RulesLoadResult( StreamUtils.readAsString(cacheResult.getData()), RulesLoadResult.Reason.SUCCESS); } /** * Gets the cache name that will be used for storing and retrieving the rules when using * operations of this class. * * @return cache name that will be used for storing and retrieving the rules. */ @NonNull public String getCacheName() { return cacheName; } private RulesLoadResult handleDownloadResponse( final String url, final HttpConnecting response) { if (response == null) { Log.trace(TAG, cacheName, "Received null response."); return new RulesLoadResult(null, RulesLoadResult.Reason.NO_DATA); } switch (response.getResponseCode()) { case HttpURLConnection.HTTP_OK: return extractRules( url, response.getInputStream(), extractMetadataFromResponse(response)); case HttpURLConnection.HTTP_NOT_MODIFIED: return new RulesLoadResult(null, RulesLoadResult.Reason.NOT_MODIFIED); case HttpURLConnection.HTTP_NOT_FOUND: default: Log.trace( TAG, cacheName, "Received download response: %s", response.getResponseCode()); return new RulesLoadResult(null, RulesLoadResult.Reason.NO_DATA); } } /** * Responsible for reading and extracting {@code zipContentStream} and returning a {@code * RulesDownloadResult} with rules. if successful. If the extraction is unsuccessful, returns a * {@code RulesDownloadResult} with the error reason. * * @param key the key that will be used for e * @param zipContentStream the zip stream that will need to be processed * @param metadata any metadata associated with the zipContentStream */ private RulesLoadResult extractRules( final String key, final InputStream zipContentStream, final Map<String, String> metadata) { if (zipContentStream == null) { Log.debug(TAG, cacheName, "Zip content stream is null"); return new RulesLoadResult(null, RulesLoadResult.Reason.NO_DATA); } // Attempt to create a temporary directory for copying the zipContentStream if (!rulesZipProcessingHelper.createTemporaryRulesDirectory(key)) { Log.debug( TAG, cacheName, "Cannot access application cache directory to create temp dir."); return new RulesLoadResult(null, RulesLoadResult.Reason.CANNOT_CREATE_TEMP_DIR); } // Copy the content of zipContentStream into the previously created temporary folder if (!rulesZipProcessingHelper.storeRulesInTemporaryDirectory(key, zipContentStream)) { Log.debug(TAG, cacheName, "Cannot read response content into temp dir."); return new RulesLoadResult(null, RulesLoadResult.Reason.CANNOT_STORE_IN_TEMP_DIR); } // Extract the rules zip final String rules = rulesZipProcessingHelper.unzipRules(key); if (rules == null) { Log.debug(TAG, cacheName, "Failed to extract rules response zip into temp dir."); return new RulesLoadResult(null, RulesLoadResult.Reason.ZIP_EXTRACTION_FAILED); } // Cache the extracted contents final CacheEntry cacheEntry = new CacheEntry( new ByteArrayInputStream(rules.getBytes(StandardCharsets.UTF_8)), CacheExpiry.never(), metadata); final boolean cached = ServiceProvider.getInstance().getCacheService().set(cacheName, key, cacheEntry); if (!cached) { Log.debug(TAG, cacheName, "Could not cache rules from source %s", key); } // Delete the temporary directory created for processing rulesZipProcessingHelper.deleteTemporaryDirectory(key); return new RulesLoadResult(rules, RulesLoadResult.Reason.SUCCESS); } /** * Extracts the response properties (like {@code HTTP_HEADER_ETAG} , {@code * HTTP_HEADER_LAST_MODIFIED} that are useful as cache metadata. * * @param response the {@code HttpConnecting} from where the response properties should be * extracted from * @return a map of metadata keys and their values as obtained from the {@code response} */ private HashMap<String, String> extractMetadataFromResponse(final HttpConnecting response) { final HashMap<String, String> metadata = new HashMap<>(); final String lastModifiedProp = response.getResponsePropertyValue(HTTP_HEADER_LAST_MODIFIED); final Date lastModifiedDate = TimeUtils.parseRFC2822Date( lastModifiedProp, TimeZone.getTimeZone("GMT"), Locale.US); final String lastModifiedMetadata = lastModifiedDate == null ? String.valueOf(new Date(0L).getTime()) : String.valueOf(lastModifiedDate.getTime()); metadata.put(HTTP_HEADER_LAST_MODIFIED, lastModifiedMetadata); final String eTagProp = response.getResponsePropertyValue(HTTP_HEADER_ETAG); metadata.put(HTTP_HEADER_ETAG, eTagProp == null ? "" : eTagProp); return metadata; } /** * Creates http headers for conditional fetching, based on the metadata of the {@code * CacheResult} provided. * * @param cacheResult the cache result whose metadata should be used for finding headers * @return a map of headers (HTTP_HEADER_IF_MODIFIED_SINCE, HTTP_HEADER_IF_NONE_MATCH) that can * be used while fetching any modified content. */ private Map<String, String> extractHeadersFromCache(final CacheResult cacheResult) { final Map<String, String> headers = new HashMap<>(); if (cacheResult == null) { return headers; } final Map<String, String> metadata = cacheResult.getMetadata(); final String eTag = metadata == null ? "" : metadata.get(HTTP_HEADER_ETAG); headers.put(HTTP_HEADER_IF_NONE_MATCH, eTag != null ? eTag : ""); // Last modified in cache metadata is stored in epoch string. So Convert it to RFC-2822 date // format. final String lastModified = metadata == null ? null : metadata.get(HTTP_HEADER_LAST_MODIFIED); long lastModifiedEpoch; try { lastModifiedEpoch = lastModified != null ? Long.parseLong(lastModified) : 0L; } catch (final NumberFormatException e) { lastModifiedEpoch = 0L; } final String ifModifiedSince = TimeUtils.getRFC2822Date(lastModifiedEpoch, TimeZone.getTimeZone("GMT"), Locale.US); headers.put(HTTP_HEADER_IF_MODIFIED_SINCE, ifModifiedSince); return headers; } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/AppResourceStore.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal import com.adobe.marketing.mobile.services.ServiceProvider internal object AppResourceStore { private const val DATASTORE_NAME = "ADOBE_MOBILE_APP_STATE" private const val SMALL_ICON_RESOURCE_ID_KEY = "SMALL_ICON_RESOURCE_ID" private const val LARGE_ICON_RESOURCE_ID_KEY = "LARGE_ICON_RESOURCE_ID" @Volatile private var smallIconResourceID = -1 @Volatile private var largeIconResourceID = -1 /** * Sets the resource Id for small icon. * * @param resourceID the resource Id of the icon */ @JvmName("setSmallIconResourceID") internal fun setSmallIconResourceID(resourceID: Int) { smallIconResourceID = resourceID val dataStore = ServiceProvider.getInstance().dataStoreService.getNamedCollection( DATASTORE_NAME ) dataStore?.setInt(SMALL_ICON_RESOURCE_ID_KEY, smallIconResourceID) } /** * Returns the resource Id for small icon if it was set by `setSmallIconResourceID`. * * @return a `int` value if it has been set, otherwise -1 */ @JvmName("getSmallIconResourceID") internal fun getSmallIconResourceID(): Int { if (smallIconResourceID == -1) { val dataStore = ServiceProvider.getInstance().dataStoreService.getNamedCollection( DATASTORE_NAME ) if (dataStore != null) { smallIconResourceID = dataStore.getInt(SMALL_ICON_RESOURCE_ID_KEY, -1) } } return smallIconResourceID } /** * Sets the resource Id for large icon. * * @param resourceID the resource Id of the icon */ @JvmName("setLargeIconResourceID") internal fun setLargeIconResourceID(resourceID: Int) { largeIconResourceID = resourceID val dataStore = ServiceProvider.getInstance().dataStoreService.getNamedCollection( DATASTORE_NAME ) dataStore?.setInt(LARGE_ICON_RESOURCE_ID_KEY, largeIconResourceID) } /** * Returns the resource Id for large icon if it was set by `setLargeIconResourceID`. * * @return a `int` value if it has been set, otherwise -1 */ @JvmName("getLargeIconResourceID") internal fun getLargeIconResourceID(): Int { if (largeIconResourceID == -1) { val dataStore = ServiceProvider.getInstance().dataStoreService.getNamedCollection( DATASTORE_NAME ) if (dataStore != null) { largeIconResourceID = dataStore.getInt(LARGE_ICON_RESOURCE_ID_KEY, -1) } } return largeIconResourceID } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/CoreConstants.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal internal object CoreConstants { const val LOG_TAG = "MobileCore" const val VERSION = "3.2.0" object EventDataKeys { /** * Holds `EventData` keys for the `Analytics` module. */ object Analytics { const val TRACK_ACTION = "action" const val TRACK_STATE = "state" const val CONTEXT_DATA = "contextdata" } /** * Holds `EventData` keys for the `Configuration` module. */ object Configuration { const val GLOBAL_CONFIG_PRIVACY = "global.privacy" // Configuration EventData Keys const val CONFIGURATION_REQUEST_CONTENT_JSON_APP_ID = "config.appId" const val CONFIGURATION_REQUEST_CONTENT_JSON_FILE_PATH = "config.filePath" const val CONFIGURATION_REQUEST_CONTENT_JSON_ASSET_FILE = "config.assetFile" const val CONFIGURATION_REQUEST_CONTENT_UPDATE_CONFIG = "config.update" const val CONFIGURATION_REQUEST_CONTENT_CLEAR_UPDATED_CONFIG = "config.clearUpdates" const val CONFIGURATION_REQUEST_CONTENT_RETRIEVE_CONFIG = "config.getData" const val CONFIGURATION_RESPONSE_IDENTITY_ALL_IDENTIFIERS = "config.allIdentifiers" } /** * Holds `EventData` keys for the `Identity` module. */ object Identity { const val ADVERTISING_IDENTIFIER = "advertisingidentifier" const val PUSH_IDENTIFIER = "pushidentifier" } /** * Holds `EventData` keys for the `Lifecycle` module. */ object Lifecycle { const val ADDITIONAL_CONTEXT_DATA = "additionalcontextdata" const val LIFECYCLE_ACTION_KEY = "action" const val LIFECYCLE_START = "start" const val LIFECYCLE_PAUSE = "pause" } /** * Holds `EventData` keys for the `Signal` module. */ object Signal { const val SIGNAL_CONTEXT_DATA = "contextdata" } } /** * Holds `Wrapper` constants */ object Wrapper { object Name { const val REACT_NATIVE = "React Native" const val FLUTTER = "Flutter" const val CORDOVA = "Cordova" const val UNITY = "Unity" const val XAMARIN = "Xamarin" const val NONE = "None" } object Type { const val REACT_NATIVE = "R" const val FLUTTER = "F" const val CORDOVA = "C" const val UNITY = "U" const val XAMARIN = "X" const val NONE = "N" } } object EventNames { const val ANALYTICS_TRACK = "Analytics Track" const val COLLECT_PII = "Collect PII" const val COLLECT_DATA = "Collect Data" const val CONFIGURE_WITH_APP_ID = "Configure with App ID" const val CONFIGURE_WITH_FILE_PATH = "Configure with File Path" const val CLEAR_UPDATED_CONFIGURATION = "Clear Updated Configuration" const val CONFIGURATION_REQUEST = "Configuration Request" const val CONFIGURATION_RESPONSE = "Configuration Response" const val CONFIGURATION_UPDATE = "Configuration Update" const val GET_SDK_IDENTITIES = "Get SDK Identities" const val LIFECYCLE_PAUSE = "Lifecycle Pause" const val LIFECYCLE_RESUME = "Lifecycle Resume" const val PRIVACY_STATUS_REQUEST = "Privacy Status Request" const val SET_PUSH_IDENTIFIER = "Set Push Identifier" const val SET_ADVERTISING_IDENTIFIER = "Set Advertising Identifier" const val RESET_IDENTITIES_REQUEST = "Reset Identities Request" } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/DataMarshaller.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import com.adobe.marketing.mobile.services.Log /** The util class to marshal data from [Activity]. */ internal object DataMarshaller { private const val LOG_TAG = "DataMarshaller" private const val DEEPLINK_KEY = "deeplink" private const val LEGACY_PUSH_MESSAGE_ID = "adb_m_id" private const val PUSH_MESSAGE_ID_KEY = "pushmessageid" private const val NOTIFICATION_IDENTIFIER_KEY = "NOTIFICATION_IDENTIFIER" private const val LOCAL_NOTIFICATION_ID_KEY = "notificationid" private const val ADOBE_QUERY_KEYS_PREVIEW_TOKEN = "at_preview_token" private const val ADOBE_QUERY_KEYS_PREVIEW_URL = "at_preview_endpoint" private const val ADOBE_QUERY_KEYS_DEEPLINK_ID = "a.deeplink.id" private val adobeQueryKeys = arrayListOf( ADOBE_QUERY_KEYS_DEEPLINK_ID, ADOBE_QUERY_KEYS_PREVIEW_TOKEN, ADOBE_QUERY_KEYS_PREVIEW_URL ) /** * Marshal an [Activity] instance and returns a data map * * @param activity Instance of an [Activity]. * @return map of marshalled data */ @JvmStatic fun marshal(activity: Activity?): Map<String, Any>? { activity ?: return null val intent = activity.intent ?: return null val ret = mutableMapOf<String, Any>() marshalIntentExtras(intent, ret) marshalIntentData(intent, ret) return ret } /** * Marshal an Intent's [Bundle] of extras into a generic data map. * Remove adobe specific keys from the bundle. * * @param intent [Intent] * @param marshalledData [Map] to add the marshalled data */ private fun marshalIntentExtras(intent: Intent, marshalledData: MutableMap<String, Any>) { val extraBundle = intent.extras ?: return extraBundle.keySet()?.forEach { key -> val newKey = when (key) { LEGACY_PUSH_MESSAGE_ID -> PUSH_MESSAGE_ID_KEY NOTIFICATION_IDENTIFIER_KEY -> LOCAL_NOTIFICATION_ID_KEY else -> key } try { val value = extraBundle[key] if (value?.toString()?.isNotEmpty() == true) { marshalledData[newKey] = value } } catch (e: Exception) { Log.error(CoreConstants.LOG_TAG, LOG_TAG, "Failed to retrieve data (key = $key) from Activity, error is: ${e.message}") } } extraBundle.remove(LEGACY_PUSH_MESSAGE_ID) extraBundle.remove(NOTIFICATION_IDENTIFIER_KEY) } /** * Marshal an Intent's data uri into a generic data map. * This function also removes adobe specific keys from the map. * * @param intent [Intent] * @param marshalledData [Map] to add the marshalled data */ private fun marshalIntentData(intent: Intent, marshalledData: MutableMap<String, Any>) { val data = intent.data ?: return if (data.toString().isEmpty()) { return } Log.trace(CoreConstants.LOG_TAG, LOG_TAG, "Receiving the Activity Uri $data") marshalledData[DEEPLINK_KEY] = data.toString() // This will remove the adobe specific keys from the intent data // This ensures that if this intent is marshaled again, we will not track // duplicate data if (data.containAdobeQueryKeys()) { intent.data = data.cleanAdobeQueryKeys() } } /** * Check if the URI contains the [adobeQueryKeys] keys * * @return true if the URI contains the Adobe specific query parameters */ private fun Uri.containAdobeQueryKeys(): Boolean { if (!isHierarchical) { return false } val queryParams = queryParameterNames ?: return false return adobeQueryKeys.any { queryParams.contains(it) } } /** * Remove the [adobeQueryKeys] query params from the URI if found. * * @return The cleaned URI */ private fun Uri.cleanAdobeQueryKeys(): Uri { if (!isHierarchical) { return this } try { val queryParamsNames = this.queryParameterNames ?: return this if (queryParamsNames.isEmpty()) { return this } val cleanUriBuilder = buildUpon() cleanUriBuilder.clearQuery() for (key in queryParamsNames) { if (!adobeQueryKeys.contains(key)) { getQueryParameters(key)?.forEach { cleanUriBuilder.appendQueryParameter(key, it) } } } return cleanUriBuilder.build() } catch (e: UnsupportedOperationException) { // AMSDK-8863 return this } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/configuration/MobileIdentitiesProvider.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.configuration import androidx.annotation.VisibleForTesting import com.adobe.marketing.mobile.Event import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.SharedStateResolution import com.adobe.marketing.mobile.SharedStateResult import com.adobe.marketing.mobile.SharedStateStatus import com.adobe.marketing.mobile.VisitorID import com.adobe.marketing.mobile.internal.util.VisitorIDSerializer import com.adobe.marketing.mobile.util.DataReader import org.json.JSONException import org.json.JSONObject /** * Responsible for providing the mobile identities known to the sdk from all extensions. */ internal object MobileIdentitiesProvider { // JSON key constants private const val JSON_KEY_COMPANY_CONTEXTS = "companyContexts" private const val JSON_KEY_USERS = "users" private const val JSON_KEY_USER_IDS = "userIDs" private const val JSON_KEY_NAMESPACE = "namespace" private const val JSON_KEY_VALUE = "value" private const val JSON_KEY_TYPE = "type" // JSON value constants for SDKIdentifier namespace private const val JSON_VALUE_NAMESPACE_COMPANY_CONTEXTS = "imsOrgID" private const val JSON_VALUE_NAMESPACE_ANALYTICS_AID = "AVID" private const val JSON_VALUE_NAMESPACE_AUDIENCE_UUID = "0" private const val JSON_VALUE_NAMESPACE_MCID = "4" private const val JSON_VALUE_NAMESPACE_TARGET_THIRD_PARTY_ID = "3rdpartyid" private const val JSON_VALUE_NAMESPACE_TARGET_TNTID = "tntid" private const val JSON_VALUE_NAMESPACE_USER_IDENTIFIER = "vid" private const val JSON_VALUE_NAMESPACE_MCPNS_DPID = "20919" // JSON value constants for SDKIdentifier type private const val JSON_VALUE_TYPE_ANALYTICS = "analytics" private const val JSON_VALUE_TYPE_INTEGRATION_CODE = "integrationCode" private const val JSON_VALUE_TYPE_TARGET = "target" private const val JSON_VALUE_TYPE_NAMESPACE_ID = "namespaceId" private val REQUIRED_READY_EXTENSIONS = listOf( SharedStateKeys.Analytics.EXTENSION_NAME, SharedStateKeys.Audience.EXTENSION_NAME, SharedStateKeys.Configuration.EXTENSION_NAME, SharedStateKeys.Target.EXTENSION_NAME, SharedStateKeys.Identity.EXTENSION_NAME ) @VisibleForTesting internal object SharedStateKeys { internal object Analytics { internal const val EXTENSION_NAME = "com.adobe.module.analytics" internal const val ANALYTICS_ID = "aid" internal const val VISITOR_IDENTIFIER = "vid" } internal object Audience { internal const val EXTENSION_NAME = "com.adobe.module.audience" internal const val DPID = "dpid" internal const val DPUUID = "dpuuid" internal const val UUID = "uuid" } internal object Identity { internal const val EXTENSION_NAME = "com.adobe.module.identity" internal const val MID = "mid" internal const val VISITOR_IDS_LIST = "visitoridslist" internal const val ADVERTISING_IDENTIFIER = "advertisingidentifier" internal const val PUSH_IDENTIFIER = "pushidentifier" } internal object Target { internal const val EXTENSION_NAME = "com.adobe.module.target" internal const val TNT_ID = "tntid" internal const val THIRD_PARTY_ID = "thirdpartyid" } internal object Configuration { internal const val EXTENSION_NAME = "com.adobe.module.configuration" internal const val CONFIG_EXPERIENCE_CLOUD_ORG_ID = "experienceCloud.org" } } /** * Represents an identifier known to the SDK */ private data class ID(val namespace: String, val value: String, val type: String) /** * Collects all the identities from various extensions and packages them into a JSON string * * @param event the [Event] generated by the GetSDKIdentities API * @param extensionApi the extensionApi used for fetching the states */ internal fun collectSdkIdentifiers(event: Event, extensionApi: ExtensionApi): String { // Collect all UserIDs val identifiers = mutableListOf<ID>() identifiers.addAll(getAnalyticsIdentifiers(event, extensionApi)) identifiers.addAll(getAudienceIdentifiers(event, extensionApi)) identifiers.addAll(getVisitorIdentifiers(event, extensionApi)) identifiers.addAll(getTargetIdentifiers(event, extensionApi)) val identifierMaps = identifiers.map { mapOf( JSON_KEY_NAMESPACE to it.namespace, JSON_KEY_VALUE to it.value, JSON_KEY_TYPE to it.type ) } // Collect company contexts val companyContexts: MutableList<Map<String, String>> = mutableListOf() getCompanyContext(event, extensionApi)?.also { orgId -> companyContexts.add( mapOf( JSON_KEY_NAMESPACE to JSON_VALUE_NAMESPACE_COMPANY_CONTEXTS, JSON_KEY_VALUE to orgId ) ) } // Prepare SDK Identities Json val sdkIdentities: MutableMap<String, Any?> = mutableMapOf() if (companyContexts.isNotEmpty()) sdkIdentities[JSON_KEY_COMPANY_CONTEXTS] = companyContexts if (identifierMaps.isNotEmpty()) sdkIdentities[JSON_KEY_USERS] = listOf(mapOf(JSON_KEY_USER_IDS to identifierMaps)) val sdkIdentitiesJson = try { JSONObject(sdkIdentities).toString() } catch (e: JSONException) { JSONObject().toString() } return sdkIdentitiesJson } /** * Gets the required identities from Identity extension. * * @param event the event at which the shared state is to be retrieved * @param extensionApi the [ExtensionApi] used to retrieve the shared state * @return a [List] of [ID]'s populated using Identity shared state */ private fun getVisitorIdentifiers( event: Event, extensionApi: ExtensionApi ): List<ID> { val visitorIdentifiers = mutableListOf<ID>() val identitySharedState = getSharedState(SharedStateKeys.Identity.EXTENSION_NAME, event, extensionApi) // MID DataReader.optString(identitySharedState?.value, SharedStateKeys.Identity.MID, null) ?.also { marketingCloudId -> visitorIdentifiers.add( ID( JSON_VALUE_NAMESPACE_MCID, marketingCloudId, JSON_VALUE_TYPE_NAMESPACE_ID ) ) } // Visitor Id list DataReader.optTypedList( Map::class.java, identitySharedState?.value, SharedStateKeys.Identity.VISITOR_IDS_LIST, emptyList() )?.also { customVisitorIDs -> val visitorIDs: List<VisitorID> = VisitorIDSerializer.convertToVisitorIds(customVisitorIDs) visitorIDs.forEach { visitorID -> if (!visitorID.id.isNullOrEmpty()) { visitorIdentifiers.add( ID( visitorID.idType, visitorID.id, JSON_VALUE_TYPE_INTEGRATION_CODE ) ) } } } // push identifier DataReader.optString( identitySharedState?.value, SharedStateKeys.Identity.PUSH_IDENTIFIER, null )?.also { pushIdentifier -> if (pushIdentifier.isNotEmpty()) { visitorIdentifiers.add( ID( JSON_VALUE_NAMESPACE_MCPNS_DPID, pushIdentifier, JSON_VALUE_TYPE_INTEGRATION_CODE ) ) } } return visitorIdentifiers } /** * Gets the required identities from Analytics extension. * * @param event the event at which the shared state is to be retrieved * @param extensionApi the [ExtensionApi] used to retrieve the shared state * @return a [List] of [ID]'s populated using Analytics shared state */ private fun getAnalyticsIdentifiers( event: Event, extensionApi: ExtensionApi ): List<ID> { val analyticsSharedState = getSharedState(SharedStateKeys.Analytics.EXTENSION_NAME, event, extensionApi) val analyticsIdentifiers = mutableListOf<ID>() if (!isSharedStateSet(analyticsSharedState)) return analyticsIdentifiers // Analytics ID DataReader.optString( analyticsSharedState?.value, SharedStateKeys.Analytics.ANALYTICS_ID, null )?.also { aid -> if (aid.isNotEmpty()) { analyticsIdentifiers.add( ID( JSON_VALUE_NAMESPACE_ANALYTICS_AID, aid, JSON_VALUE_TYPE_INTEGRATION_CODE ) ) } } // Visitor ID DataReader.optString( analyticsSharedState?.value, SharedStateKeys.Analytics.VISITOR_IDENTIFIER, null )?.also { vid -> if (vid.isNotEmpty()) { analyticsIdentifiers.add( ID( JSON_VALUE_NAMESPACE_USER_IDENTIFIER, vid, JSON_VALUE_TYPE_ANALYTICS ) ) } } return analyticsIdentifiers } /** * Gets the required identities from Audience extension. * * @param event the event at which the shared state is to be retrieved * @param extensionApi the [ExtensionApi] used to retrieve the shared state * @return a [List] of [ID]'s populated using Audience shared state */ private fun getAudienceIdentifiers( event: Event, extensionApi: ExtensionApi ): List<ID> { val audienceSharedState = getSharedState(SharedStateKeys.Audience.EXTENSION_NAME, event, extensionApi) val audienceIdentifiers = mutableListOf<ID>() if (!isSharedStateSet(audienceSharedState)) return audienceIdentifiers // Data provider unique user id DataReader.optString(audienceSharedState?.value, SharedStateKeys.Audience.DPUUID, null) ?.also { dpuuid -> if (dpuuid.isNotEmpty()) { val dpid = DataReader.optString( audienceSharedState?.value, SharedStateKeys.Audience.DPID, "" ) audienceIdentifiers.add(ID(dpid, dpuuid, JSON_VALUE_TYPE_NAMESPACE_ID)) } } // Audience unique user id DataReader.optString(audienceSharedState?.value, SharedStateKeys.Audience.UUID, null) ?.also { uuid -> if (uuid.isNotEmpty()) { audienceIdentifiers.add( ID( JSON_VALUE_NAMESPACE_AUDIENCE_UUID, uuid, JSON_VALUE_TYPE_NAMESPACE_ID ) ) } } return audienceIdentifiers } /** * Gets the required identities from Target extension. * * @param event the event at which the shared state is to be retrieved * @param extensionApi the [ExtensionApi] used to retrieve the shared state * @return a [List] of [ID]'s populated using Target shared state */ private fun getTargetIdentifiers( event: Event, extensionApi: ExtensionApi ): List<ID> { val targetIdentifiers = mutableListOf<ID>() val targetSharedState = getSharedState(SharedStateKeys.Target.EXTENSION_NAME, event, extensionApi) if (!isSharedStateSet(targetSharedState)) return targetIdentifiers // Target user identifier DataReader.optString( targetSharedState?.value, SharedStateKeys.Target.TNT_ID, null )?.also { tntId -> if (tntId.isNotEmpty()) { targetIdentifiers.add( ID( JSON_VALUE_NAMESPACE_TARGET_TNTID, tntId, JSON_VALUE_TYPE_TARGET ) ) } } // Target 3rd party ID DataReader.optString( targetSharedState?.value, SharedStateKeys.Target.THIRD_PARTY_ID, null )?.also { thirdPartyId -> if (thirdPartyId.isNotEmpty()) { targetIdentifiers.add( ID( JSON_VALUE_NAMESPACE_TARGET_THIRD_PARTY_ID, thirdPartyId, JSON_VALUE_TYPE_TARGET ) ) } } return targetIdentifiers } /** * Gets the list of orgId's from Configuration extension. * * @param event the event at which the shared state is to be retrieved * @param extensionApi the [ExtensionApi] used to retrieve the shared state * @return a organization Id's as populated using Configuration shared state */ private fun getCompanyContext( event: Event, extensionApi: ExtensionApi ): String? { var orgId: String? = null val configurationSharedState = getSharedState(SharedStateKeys.Configuration.EXTENSION_NAME, event, extensionApi) if (!isSharedStateSet(configurationSharedState)) { return orgId } DataReader.optString( configurationSharedState?.value, SharedStateKeys.Configuration.CONFIG_EXPERIENCE_CLOUD_ORG_ID, null )?.also { marketingCloudOrgId -> if (marketingCloudOrgId.isNotEmpty()) { orgId = marketingCloudOrgId } } return orgId } /** * Gets the shared state for the extension with name [name] at event [event] * * @param name the name of the extension for which the shared state is to be fetched * @param event the event at which the shared state is to be retrieved * @param extensionApi the [ExtensionApi] used to retrieve the shared state * * @return the [SharedStateResult] for the extension if available; null otherwise */ private fun getSharedState( name: String, event: Event, extensionApi: ExtensionApi ): SharedStateResult? { return extensionApi.getSharedState(name, event, false, SharedStateResolution.ANY) } private fun isSharedStateSet(sharedState: SharedStateResult?): Boolean { return sharedState?.status == SharedStateStatus.SET } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/configuration/ConfigurationDownloader.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.configuration import com.adobe.marketing.mobile.internal.util.toMap import com.adobe.marketing.mobile.services.HttpConnecting import com.adobe.marketing.mobile.services.HttpMethod import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.NetworkCallback import com.adobe.marketing.mobile.services.NetworkRequest import com.adobe.marketing.mobile.services.ServiceProvider import com.adobe.marketing.mobile.services.caching.CacheEntry import com.adobe.marketing.mobile.services.caching.CacheExpiry import com.adobe.marketing.mobile.services.caching.CacheService import com.adobe.marketing.mobile.util.StreamUtils import com.adobe.marketing.mobile.util.TimeUtils import com.adobe.marketing.mobile.util.UrlUtils import org.json.JSONException import org.json.JSONObject import org.json.JSONTokener import java.io.InputStream import java.lang.NumberFormatException import java.net.HttpURLConnection import java.util.Date import java.util.Locale import java.util.TimeZone /** * Responsible for downloading configuration json file and processing it to provide a * usable configuration for the app implementing AEP SDK. */ internal class ConfigurationDownloader { companion object { const val LOG_TAG = "ConfigurationDownloader" const val HTTP_HEADER_IF_MODIFIED_SINCE = "If-Modified-Since" const val HTTP_HEADER_IF_NONE_MATCH = "If-None-Match" const val HTTP_HEADER_LAST_MODIFIED = "Last-Modified" const val HTTP_HEADER_ETAG = "ETag" internal const val CONFIG_CACHE_NAME = "config" private const val DEFAULT_CONNECTION_TIMEOUT_MS = 10000 private const val DEFAULT_READ_TIMEOUT_MS = 10000 } /** * Triggers the download of configuration from [url] and invokes * [completionCallback] after processing the downloaded content. * Internally, a successful download result is cached and it accessible via [CacheService] * from the cache name [CONFIG_CACHE_NAME] and key [url] * * @param url the URL from which the configuration should be downloaded * @param completionCallback the callback to invoke with the parsed/processed configuration * */ fun download( url: String, completionCallback: (Map<String, Any?>?) -> Unit ) { if (!UrlUtils.isValidUrl(url)) { completionCallback.invoke(null) return } val cacheResult = ServiceProvider.getInstance().cacheService.get(CONFIG_CACHE_NAME, url) // Compute headers val headers: MutableMap<String, String> = HashMap() if (cacheResult != null) { // use the HTTP_HEADER_ETAG of cached result to populate // HTTP_HEADER_IF_NONE_MATCH for the request val eTag = cacheResult.metadata?.get(HTTP_HEADER_ETAG) ?: "" headers[HTTP_HEADER_IF_NONE_MATCH] = eTag // Use HTTP_HEADER_LAST_MODIFIED of the cached result to // populate HTTP_HEADER_IF_MODIFIED_SINCE for the reqest // Last modified in cache metadata is stored in epoch string. So Convert it to RFC-2822 date format. val lastModified = cacheResult.metadata?.get(HTTP_HEADER_LAST_MODIFIED) val lastModifiedEpoch = try { lastModified?.toLong() ?: 0L } catch (e: NumberFormatException) { 0L } val ifModifiedSince = TimeUtils.getRFC2822Date( lastModifiedEpoch, TimeZone.getTimeZone("GMT"), Locale.US ) headers[HTTP_HEADER_IF_MODIFIED_SINCE] = ifModifiedSince } val networkRequest = NetworkRequest( url, HttpMethod.GET, null, headers, DEFAULT_CONNECTION_TIMEOUT_MS, DEFAULT_READ_TIMEOUT_MS ) val networkCallback = NetworkCallback { response: HttpConnecting? -> val config = handleDownloadResponse(url, response) response?.close() completionCallback.invoke(config) } ServiceProvider.getInstance().networkService.connectAsync(networkRequest, networkCallback) } /** * Handles the processing a new configuration from [response] or fetching cached configuration * based on [HttpConnecting.responseCode] of the [response] * * @param url the url for which the [response] is obtained. Used for caching the downloaded content. * @param response the response which is to be processed * @return a map representation of the json configuration obtained from [response] */ private fun handleDownloadResponse(url: String, response: HttpConnecting?): Map<String, Any?>? { if (response == null) { Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Received a null response." ) // Return null here to trigger a retry as this is likely an internal failure // in the network service return null } return when (response.responseCode) { HttpURLConnection.HTTP_OK -> { val metadata = mutableMapOf<String, String>() val lastModifiedProp = response.getResponsePropertyValue(HTTP_HEADER_LAST_MODIFIED) val lastModifiedDate = TimeUtils.parseRFC2822Date(lastModifiedProp, TimeZone.getTimeZone("GMT"), Locale.US) ?: Date(0L) val lastModifiedMetadata = lastModifiedDate.time.toString() metadata[HTTP_HEADER_LAST_MODIFIED] = lastModifiedMetadata val eTagProp = response.getResponsePropertyValue(HTTP_HEADER_ETAG) metadata[HTTP_HEADER_ETAG] = eTagProp ?: "" // extract the rules file and return. processDownloadedConfig(url, response.inputStream, metadata) } HttpURLConnection.HTTP_NOT_MODIFIED -> { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Configuration from $url has not been modified. Fetching from cache." ) val cacheResult = ServiceProvider.getInstance().cacheService.get(CONFIG_CACHE_NAME, url) processDownloadedConfig(url, cacheResult?.data, cacheResult?.metadata) } else -> { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Download result :${response.responseCode}" ) null } } } private fun processDownloadedConfig( url: String, response: InputStream?, metadata: Map<String, String?>? ): Map<String, Any?>? { val content: String? = StreamUtils.readAsString(response) return when { content == null -> null content.isEmpty() -> { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Downloaded configuration is empty." ) emptyMap() } else -> { try { // Downloaded configuration is expected to be a JSON string. val downloadedConfig = JSONObject(JSONTokener(content)) val configMap = downloadedConfig.toMap() // Cache the downloaded configuration before returning val cacheEntry = CacheEntry(content.byteInputStream(), CacheExpiry.never(), metadata) ServiceProvider.getInstance().cacheService.set(CONFIG_CACHE_NAME, url, cacheEntry) configMap } catch (exception: JSONException) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Exception processing downloaded configuration $exception" ) null } } } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/configuration/ConfigurationStateManager.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.configuration import androidx.annotation.VisibleForTesting import com.adobe.marketing.mobile.internal.util.FileUtils import com.adobe.marketing.mobile.internal.util.toMap import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.NamedCollection import com.adobe.marketing.mobile.services.ServiceProvider import com.adobe.marketing.mobile.services.caching.CacheResult import com.adobe.marketing.mobile.util.StreamUtils import org.json.JSONException import org.json.JSONObject import org.json.JSONTokener import java.io.File import java.io.InputStream import java.util.Date /** * Responsible for storing, retrieving and maintaining the latest configuration state for the environment * based on inputs from different sources. */ internal class ConfigurationStateManager { companion object { private const val LOG_TAG = "ConfigurationStateManager" private const val CONFIGURATION_TTL_MS = 15000L private const val BUILD_ENVIRONMENT = "build.environment" private const val ENVIRONMENT_PREFIX_DELIMITER = "__" private const val CONFIGURATION_URL_BASE = "https://assets.adobedtm.com/%s.json" internal const val DATASTORE_KEY = "AdobeMobile_ConfigState" internal const val PERSISTED_OVERRIDDEN_CONFIG = "config.overridden.map" internal const val CONFIG_MANIFEST_APPID_KEY = "ADBMobileAppID" internal const val PERSISTED_APPID = "config.appID" internal const val CONFIG_BUNDLED_FILE_NAME = "ADBMobileConfig.json" } private val appIdManager: AppIdManager /** * Responsible for downloading the configuration from a given appId. */ private val configDownloader: ConfigurationDownloader /** * Maintains the configuration that has not been subjected to programmatic * configuration changes. */ private val unmergedConfiguration: MutableMap<String, Any?> = mutableMapOf() /** * Maintains the current programmatic configuration. */ private val programmaticConfiguration: MutableMap<String, Any?> = mutableMapOf() /** * Maintains the entire config (i.e with environment keys). */ @VisibleForTesting internal val currentConfiguration: MutableMap<String, Any?> = mutableMapOf() /** * Maintains the configuration associated with the current environment. * Determined by the [BUILD_ENVIRONMENT] key in the [currentConfiguration] */ internal var environmentAwareConfiguration: Map<String, Any?> = mapOf() private set /** * Maintains a mapping between appId and the most recent download time when the config for that * appId has been downloaded */ private val configDownloadMap: MutableMap<String, Date> = mutableMapOf() constructor( appIdManager: AppIdManager ) : this( appIdManager, ConfigurationDownloader() ) @VisibleForTesting internal constructor ( appIdManager: AppIdManager, configDownloader: ConfigurationDownloader ) { this.appIdManager = appIdManager this.configDownloader = configDownloader // retrieve the persisted programmatic configuration // but do not load it anywhere getPersistedProgrammaticConfig()?.let { programmaticConfiguration.putAll(it) } } /** * Loads the first configuration at launch inferred from * bundled config, cached config and programmatic configs. * * @return the initial configuration at launch */ internal fun loadInitialConfig(): Map<String, Any?> { currentConfiguration.clear() val appId: String? = appIdManager.loadAppId() val config: Map<String, Any?>? = if (appId.isNullOrEmpty()) { // Load bundled config Log.trace( ConfigurationExtension.TAG, LOG_TAG, "AppID from persistence and manifest is null." ) loadBundledConfig(CONFIG_BUNDLED_FILE_NAME) } else { loadCachedConfig(appId) ?: loadBundledConfig(CONFIG_BUNDLED_FILE_NAME) } // Replace the exiting configuration with new config. replaceConfiguration(config) return environmentAwareConfiguration } /** * Retrieves the configuration from config file bundled along with the app. * * @param bundledConfigFileName the file name of the bundled configuration * @return the configuration parsed from the bundled config file [bundledConfigFileName] if successful, * null otherwise. */ @VisibleForTesting internal fun loadBundledConfig(bundledConfigFileName: String): Map<String, Any?>? { Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Attempting to load bundled config." ) val contentStream: InputStream? = ServiceProvider.getInstance().deviceInfoService.getAsset(bundledConfigFileName) val contentString = StreamUtils.readAsString( contentStream ) if (contentString.isNullOrEmpty()) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Bundled config asset is not present/is empty. Cannot load bundled config." ) return null } return try { val bundledConfigJson = JSONObject(JSONTokener(contentString)) bundledConfigJson.toMap() } catch (exception: JSONException) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Failed to load bundled config $exception" ) null } } /** * Updates the existing configuration with the one from [fileAssetName] * * @param fileAssetName the asset file name from which new configuration * should be read * @return true if the configuration has been updated with content from [fileAssetName], * false otherwise */ internal fun updateConfigWithFileAsset(fileAssetName: String): Boolean { val config = loadBundledConfig(fileAssetName) if (config.isNullOrEmpty()) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Empty configuration found when processing JSON string." ) return false } replaceConfiguration(config) return true } /** * Updates the existing configuration with the one from [filePath] * * @param filePath the file name from which new configuration * should be read * @return true if the configuration has been updated with content from [filePath], * false otherwise */ internal fun updateConfigWithFilePath(filePath: String): Boolean { val config = getConfigFromFile(filePath) if (config == null) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Unable to read config from provided file (content is invalid)" ) return false } replaceConfiguration(config) return true } /** * Retrieves the configuration from config file specified by [filePath]. * * @param filePath the file path from which the config must be retrieved * @return the configuration as a map parsed from the file if successful, * null otherwise. */ @VisibleForTesting internal fun getConfigFromFile(filePath: String): Map<String, Any?>? { val configFile = File(filePath) val configFileContent = FileUtils.readAsString(configFile) if (configFileContent.isNullOrEmpty()) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Empty configuration from file path while configuring with file path." ) return null } val config = try { val configJson = JSONObject(JSONTokener(configFileContent)) configJson.toMap() } catch (exception: JSONException) { Log.warning( ConfigurationExtension.TAG, LOG_TAG, "Failed to parse JSON config from file while configuring with file path." ) null } if (config.isNullOrEmpty()) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Empty configuration found when processing JSON string." ) return null } return config } /** * Retrieves the persisted programmatic configuration. * * @return the persisted programmatic configuration as a map if it exists, * null otherwise. */ private fun getPersistedProgrammaticConfig(): Map<String, Any?>? { val configStore: NamedCollection = ServiceProvider.getInstance().dataStoreService.getNamedCollection(DATASTORE_KEY) val persistedConfigContent = configStore.getString(PERSISTED_OVERRIDDEN_CONFIG, null) if (persistedConfigContent.isNullOrEmpty()) return null try { val overriddenConfigObj = JSONObject(JSONTokener(persistedConfigContent)) Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Loaded persisted programmatic Configuration" ) return overriddenConfigObj.toMap() } catch (exception: JSONException) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Unable to parse the Configuration from JSON Object. Exception: ($exception)" ) } return null } /** * Retrieves configuration from a previously cached appId. * * @param appId the appId whose configuration is to be retrieved, if cached * @return configuration associated with [appId] if it was cached earlier, * null otherwise */ private fun loadCachedConfig(appId: String): Map<String, Any?>? { Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Attempting to load cached config." ) val url = String.format(CONFIGURATION_URL_BASE, appId) val cacheResult: CacheResult? = ServiceProvider.getInstance().cacheService.get( ConfigurationDownloader.CONFIG_CACHE_NAME, url ) val contentString = StreamUtils.readAsString(cacheResult?.data) if (contentString.isNullOrEmpty()) { Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Cached config is null/empty." ) return null } return try { val cachedConfig = JSONObject(JSONTokener(contentString)) cachedConfig.toMap() } catch (exception: JSONException) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Failed to load cached config $exception" ) null } } /** * Downloads and replaces the current configuration with the one associated with [appId] * * @param appId a non-null application Id which should be used for downloading the configuration * @param completion the callback to be invoked with the downloaded configuration */ internal fun updateConfigWithAppId(appId: String, completion: (Map<String, Any?>?) -> Unit) { if (appId.isBlank()) { Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Attempting to set empty App Id into persistence." ) return } appIdManager.saveAppIdToPersistence(appId) val url = String.format(CONFIGURATION_URL_BASE, appId) configDownloader.download(url) { config -> if (config != null) { // replace the configuration with downloaded content first replaceConfiguration(config) // Update the last time of config download via appID configDownloadMap[appId] = Date() // return the environment configuration completion.invoke(environmentAwareConfiguration) } else { completion.invoke(null) } } } /** * Clears any stored programmatic configuration and refreshes * the [currentConfiguration] & [environmentAwareConfiguration] with [unmergedConfiguration] */ internal fun clearProgrammaticConfig() { // Clear programmatic config from persistence val configStore: NamedCollection = ServiceProvider.getInstance().dataStoreService.getNamedCollection(DATASTORE_KEY) configStore.remove(PERSISTED_OVERRIDDEN_CONFIG) // Clear im memory programmatic config programmaticConfiguration.clear() // Update the current configuration to reflect changes in programmatic config currentConfiguration.clear() currentConfiguration.putAll(unmergedConfiguration) computeEnvironmentAwareConfig() Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Cleared programmatic configuration." ) } /** * Changes the current configuration with the [config] provided. * Note that any persisted programmatic configuration will be applied on top of [config]. * * @param config the configuration that should replace the [unmergedConfiguration] */ @VisibleForTesting internal fun replaceConfiguration(config: Map<String, Any?>?) { // Replace the unmerged programmatic config with the new config unmergedConfiguration.clear() config?.let { unmergedConfiguration.putAll(config) } // Reset the current config and apply new configuration and programmatic config incrementally currentConfiguration.clear() currentConfiguration.putAll(unmergedConfiguration) currentConfiguration.putAll(programmaticConfiguration) computeEnvironmentAwareConfig() Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Replaced configuration." ) } /** * Updates the previously persisted programmatic config with contents of [config] * * @param config the entries which must be updated in the programmatic configuration */ internal fun updateProgrammaticConfig(config: Map<String, Any?>) { // Map any config keys to their corresponding environment aware keys val mappedConfig = mapToEnvironmentAwareKeys(config) programmaticConfiguration.putAll(mappedConfig) // Save the new/modified programmatic config to persistence val configStore: NamedCollection = ServiceProvider.getInstance().dataStoreService.getNamedCollection(DATASTORE_KEY) val jsonString = JSONObject(programmaticConfiguration).toString() configStore.setString(PERSISTED_OVERRIDDEN_CONFIG, jsonString) // Update the current configuration to reflect changes in programmatic config currentConfiguration.putAll(programmaticConfiguration) computeEnvironmentAwareConfig() Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Updated programmatic configuration." ) } /** * Checks if the configuration associated with [appId] has been downloaded and is unexpired * * @return true if the configuration associated with [appId] has been downloaded and is unexpired, * false otherwise */ internal fun hasConfigExpired(appId: String): Boolean { val latestDownloadDate: Date? = configDownloadMap[appId] return latestDownloadDate == null || Date(latestDownloadDate.time + CONFIGURATION_TTL_MS) < Date() } /** * Computes the configuration for the current environment (defined by [BUILD_ENVIRONMENT] in the config) * based on [currentConfiguration] and updates [environmentAwareConfiguration] */ private fun computeEnvironmentAwareConfig() { val buildEnvironment: String = currentConfiguration[BUILD_ENVIRONMENT] as? String ?: "" // use this map to accumulate the environment aware configuration val rollingEnvironmentAwareMap = mutableMapOf<String, Any?>() // NOTE: [currentConfiguration] assumes that all config keys for an app have an associated prod key. // So it it sufficient to iterate over it and replace values by forming environment based keys. // This logic needs to change if the assumption is no longer valid. currentConfiguration.entries.forEach { entry -> val key = entry.key // We only want to construct environment keys and find environment specific values for prod keys. if (!key.startsWith(ENVIRONMENT_PREFIX_DELIMITER)) { var environmentAwareKey = getKeyForEnvironment(key, buildEnvironment) environmentAwareKey = if (currentConfiguration[environmentAwareKey] != null) { environmentAwareKey } else { key } // If a config value for the current build environment exists, use `key`'s // value with `environmentKey`'s value val value = currentConfiguration[environmentAwareKey] value?.let { rollingEnvironmentAwareMap[key] = value } } } environmentAwareConfiguration = rollingEnvironmentAwareMap } /** * Maps config keys to their respective build environment. Note that the values are not altered. * @param config the configuration to map * @return the mapped configuration with all the keys mapped to their respective build environment equivalents */ @VisibleForTesting internal fun mapToEnvironmentAwareKeys(config: Map<String, Any?>): Map<String, Any?> { val buildEnvironment: String = currentConfiguration[BUILD_ENVIRONMENT] as? String ?: return config val environmentAwareConfigMap = mutableMapOf<String, Any?>() config.entries.forEach { entry -> val key = entry.key val environmentAwareKey = getKeyForEnvironment(key, buildEnvironment) val keyToUse = if (currentConfiguration[environmentAwareKey] != null) { environmentAwareKey } else { key } // Do not alter the value, just map the key environmentAwareConfigMap[keyToUse] = entry.value } return environmentAwareConfigMap } /** * Returns the correct key from configuration json based on the build environment and base key * * For configuration, the base_key will always be the name of the production configuration value. e.g. : * - Production Key - myKeyName * - Staging Key - __stage__myKeyName * - Development Key - __dev__myKeyName * * @param baseKey the production key name to use as the base for the result * @param environment the value from build.environment in the configuration json provided by Launch * @return a string representing the correct key to use given the provided environment */ private fun getKeyForEnvironment(baseKey: String, environment: String): String { return if (environment.isEmpty()) { baseKey } else { ENVIRONMENT_PREFIX_DELIMITER + environment + ENVIRONMENT_PREFIX_DELIMITER + baseKey } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/configuration/ConfigurationExtension.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.configuration import androidx.annotation.VisibleForTesting import com.adobe.marketing.mobile.Event import com.adobe.marketing.mobile.EventSource import com.adobe.marketing.mobile.EventType import com.adobe.marketing.mobile.Extension import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.SharedStateResolver import com.adobe.marketing.mobile.internal.CoreConstants import com.adobe.marketing.mobile.internal.eventhub.EventHub import com.adobe.marketing.mobile.launch.rulesengine.LaunchRulesEngine import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.util.DataReader import java.util.concurrent.Executors import java.util.concurrent.Future import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit /** * Configuration Extension. * Responsible for retrieving the configuration of the SDK, updating the shared state and * dispatching configuration updates through the `EventHub` */ internal class ConfigurationExtension : Extension { companion object { internal const val TAG = "Configuration" private const val EXTENSION_NAME = "com.adobe.module.configuration" private const val EXTENSION_FRIENDLY_NAME = "Configuration" private const val EXTENSION_VERSION = CoreConstants.VERSION internal const val CONFIGURATION_REQUEST_CONTENT_JSON_APP_ID = "config.appId" internal const val CONFIGURATION_REQUEST_CONTENT_JSON_FILE_PATH = "config.filePath" internal const val CONFIGURATION_REQUEST_CONTENT_JSON_ASSET_FILE = "config.assetFile" internal const val CONFIGURATION_REQUEST_CONTENT_UPDATE_CONFIG = "config.update" internal const val CONFIGURATION_REQUEST_CONTENT_CLEAR_UPDATED_CONFIG = "config.clearUpdates" internal const val CONFIGURATION_REQUEST_CONTENT_RETRIEVE_CONFIG = "config.getData" internal const val CONFIGURATION_REQUEST_CONTENT_IS_INTERNAL_EVENT = "config.isinternalevent" internal const val DATASTORE_KEY = "AdobeMobile_ConfigState" internal const val RULES_CONFIG_URL = "rules.url" internal const val CONFIG_DOWNLOAD_RETRY_ATTEMPT_DELAY_MS = 5000L internal const val CONFIGURATION_RESPONSE_IDENTITY_ALL_IDENTIFIERS = "config.allIdentifiers" internal const val EVENT_STATE_OWNER = "stateowner" internal const val GLOBAL_CONFIG_PRIVACY = "global.privacy" } /** * Represents the source from which rules can be loaded. */ private enum class RulesSource { CACHE, BUNDLED, REMOTE } private val appIdManager: AppIdManager private val launchRulesEngine: LaunchRulesEngine private val configurationStateManager: ConfigurationStateManager private val configurationRulesManager: ConfigurationRulesManager private val retryWorker: ScheduledExecutorService private var retryConfigurationCounter: Int = 0 private var retryConfigTaskHandle: Future<*>? = null constructor(extensionApi: ExtensionApi) : this( extensionApi, AppIdManager(), LaunchRulesEngine("Configuration", extensionApi), Executors.newSingleThreadScheduledExecutor() ) /** * Exists only for cascading components for dependency injection. */ private constructor( extensionApi: ExtensionApi, appIdManager: AppIdManager, launchRulesEngine: LaunchRulesEngine, retryWorker: ScheduledExecutorService ) : this( extensionApi, appIdManager, launchRulesEngine, retryWorker, ConfigurationStateManager(appIdManager), ConfigurationRulesManager(launchRulesEngine) ) @VisibleForTesting internal constructor( extensionApi: ExtensionApi, appIdManager: AppIdManager, launchRulesEngine: LaunchRulesEngine, retryWorker: ScheduledExecutorService, configurationStateManager: ConfigurationStateManager, configurationRulesManager: ConfigurationRulesManager ) : super(extensionApi) { this.appIdManager = appIdManager this.launchRulesEngine = launchRulesEngine this.retryWorker = retryWorker this.configurationStateManager = configurationStateManager this.configurationRulesManager = configurationRulesManager loadInitialConfiguration() EventHub.shared.registerEventPreprocessor { e -> launchRulesEngine.processEvent(e) } } /** * Loads the initial configuration. */ private fun loadInitialConfiguration() { val appId = this.appIdManager.loadAppId() if (!appId.isNullOrBlank()) { val eventData: MutableMap<String, Any?> = mutableMapOf( CONFIGURATION_REQUEST_CONTENT_JSON_APP_ID to appId, CONFIGURATION_REQUEST_CONTENT_IS_INTERNAL_EVENT to true ) dispatchConfigurationRequest(eventData) } val initialConfig: Map<String, Any?> = this.configurationStateManager.loadInitialConfig() if (initialConfig.isNotEmpty()) { applyConfigurationChanges(RulesSource.CACHE, null) } else { Log.trace( TAG, TAG, "Initial configuration loaded is empty." ) } } /** * Sets up the Configuration extension for the SDK by registering * event listeners for processing events. */ override fun onRegistered() { super.onRegistered() // States should not be created in the constructor of the Extension. // Publish initial state that is pre-computed in the constructor when the // registration completes. val initialConfigState = configurationStateManager.environmentAwareConfiguration if (initialConfigState.isNotEmpty()) { api.createSharedState(initialConfigState, null) } api.registerEventListener( EventType.CONFIGURATION, EventSource.REQUEST_CONTENT ) { handleConfigurationRequestEvent(it) } api.registerEventListener( EventType.CONFIGURATION, EventSource.REQUEST_IDENTITY ) { retrieveSDKIdentifiers(it) } } override fun getName(): String { return EXTENSION_NAME } override fun getFriendlyName(): String { return EXTENSION_FRIENDLY_NAME } override fun getVersion(): String { return EXTENSION_VERSION } /** * Responsible for handling the incoming event requests directed towards [ConfigurationExtension]. * * @param event the event request dispatched to the [ConfigurationExtension] */ internal fun handleConfigurationRequestEvent(event: Event) { if (event.eventData == null) return when { event.eventData.containsKey(CONFIGURATION_REQUEST_CONTENT_JSON_APP_ID) -> { configureWithAppID(event, api.createPendingSharedState(event)) } event.eventData.containsKey(CONFIGURATION_REQUEST_CONTENT_JSON_ASSET_FILE) -> { configureWithFileAsset(event, api.createPendingSharedState(event)) } event.eventData.containsKey(CONFIGURATION_REQUEST_CONTENT_JSON_FILE_PATH) -> { configureWithFilePath(event, api.createPendingSharedState(event)) } event.eventData.containsKey(CONFIGURATION_REQUEST_CONTENT_UPDATE_CONFIG) -> { updateConfiguration(event, api.createPendingSharedState(event)) } event.eventData.containsKey(CONFIGURATION_REQUEST_CONTENT_CLEAR_UPDATED_CONFIG) -> { clearUpdatedConfiguration(api.createPendingSharedState(event)) } event.eventData.containsKey(CONFIGURATION_REQUEST_CONTENT_RETRIEVE_CONFIG) -> { retrieveConfiguration(event) } } } /** * Downloads the configuration file based on the appId provided with the [event] and updates * the current app configuration with the resulting downloaded configuration. * * @param event the event requesting/triggering an update to configuration with appId. * @param sharedStateResolver the resolver should be used for resolving the current state */ private fun configureWithAppID(event: Event, sharedStateResolver: SharedStateResolver?) { val appId = event.eventData?.get(CONFIGURATION_REQUEST_CONTENT_JSON_APP_ID) as? String if (appId.isNullOrBlank()) { Log.trace( TAG, TAG, "AppId in configureWithAppID event is null." ) appIdManager.removeAppIdFromPersistence() sharedStateResolver?.resolve(configurationStateManager.environmentAwareConfiguration) return } if (!configurationStateManager.hasConfigExpired(appId)) { sharedStateResolver?.resolve(configurationStateManager.environmentAwareConfiguration) return } // Check if this is an internal request ovewriting explicit configure with appId request. val isInternalEvent = DataReader.optBoolean(event.eventData, CONFIGURATION_REQUEST_CONTENT_IS_INTERNAL_EVENT, false) if (isStaleAppIdUpdateRequest(appId, isInternalEvent)) { Log.trace(TAG, TAG, "An explicit configure with AppId request has preceded this internal event.") sharedStateResolver?.resolve(configurationStateManager.environmentAwareConfiguration) return } // Stop all event processing for the extension until new configuration download is attempted api.stopEvents() configurationStateManager.updateConfigWithAppId(appId) { config -> if (config != null) { cancelConfigRetry() applyConfigurationChanges(RulesSource.REMOTE, sharedStateResolver) } else { Log.trace( TAG, TAG, "Failed to download configuration. Applying Will retry download." ) // If the configuration download fails, publish current configuration and retry download again. sharedStateResolver?.resolve(configurationStateManager.environmentAwareConfiguration) retryConfigTaskHandle = retryConfigDownload(appId) } // Start event processing again api.startEvents() } } /** * Retrieves the configuration from the file path specified in the [event]'s data and replaces * the current configuration with it. * * @param event the trigger event (whose event data contains the file path for retrieving the config) * requesting a configuration change * @param sharedStateResolver the resolver should be used for resolving the current state */ private fun configureWithFilePath(event: Event, sharedStateResolver: SharedStateResolver?) { val filePath = event.eventData?.get(CONFIGURATION_REQUEST_CONTENT_JSON_FILE_PATH) as String? if (filePath.isNullOrBlank()) { Log.warning( TAG, TAG, "Unable to read config from provided file (filePath: $filePath is invalid)" ) sharedStateResolver?.resolve(configurationStateManager.environmentAwareConfiguration) return } val result = configurationStateManager.updateConfigWithFilePath(filePath) if (result) { applyConfigurationChanges(RulesSource.REMOTE, sharedStateResolver) } else { Log.debug( TAG, TAG, "Could not update configuration from file path: $filePath" ) sharedStateResolver?.resolve(configurationStateManager.environmentAwareConfiguration) } } /** * Updates the current configuration with the content from a file asset. * * @param event which contains [CONFIGURATION_REQUEST_CONTENT_JSON_ASSET_FILE] as part of its event data * @param sharedStateResolver the resolver should be used for resolving the current state */ private fun configureWithFileAsset(event: Event, sharedStateResolver: SharedStateResolver?) { val fileAssetName = event.eventData?.get(CONFIGURATION_REQUEST_CONTENT_JSON_ASSET_FILE) as String? if (fileAssetName.isNullOrBlank()) { Log.debug( TAG, TAG, "Asset file name for configuration is null or empty." ) sharedStateResolver?.resolve(configurationStateManager.environmentAwareConfiguration) return } val result = configurationStateManager.updateConfigWithFileAsset(fileAssetName) if (result) { applyConfigurationChanges(RulesSource.REMOTE, sharedStateResolver) } else { Log.debug( TAG, TAG, "Could not update configuration from file asset: $fileAssetName" ) sharedStateResolver?.resolve(configurationStateManager.environmentAwareConfiguration) } } /** * Updates the programmatic configuration with the programmatic config in [event]'s data. * * @param event the event containing programmatic configuration that is to be applied on the * current configuration * @param sharedStateResolver the resolver should be used for resolving the current state */ private fun updateConfiguration(event: Event, sharedStateResolver: SharedStateResolver?) { val programmaticConfig: Map<String, Any?>? = DataReader.optTypedMap( Any::class.java, event.eventData, CONFIGURATION_REQUEST_CONTENT_UPDATE_CONFIG, null ) if (programmaticConfig == null) { Log.debug( TAG, TAG, "Invalid configuration. Provided configuration is null or contains non string keys." ) sharedStateResolver?.resolve(configurationStateManager.environmentAwareConfiguration) return } configurationStateManager.updateProgrammaticConfig(programmaticConfig) applyConfigurationChanges(RulesSource.REMOTE, sharedStateResolver) } /** * Clears any updates made to the configuration (more specifically the programmatic config) * maintained by the extension. * */ private fun clearUpdatedConfiguration(sharedStateResolver: SharedStateResolver?) { configurationStateManager.clearProgrammaticConfig() applyConfigurationChanges(RulesSource.REMOTE, sharedStateResolver) } /** * Dispatches an event containing the current configuration * * @param event the event to which the current configuration should be * dispatched as a response */ private fun retrieveConfiguration(event: Event) { dispatchConfigurationResponse( configurationStateManager.environmentAwareConfiguration, event ) } /** * Dispatches an event containing the current SDK Identifiers * * @param event the event to which the current SDK Identifiers should be * dispatched as a response */ @VisibleForTesting internal fun retrieveSDKIdentifiers(event: Event) { val eventData = mutableMapOf<String, Any?>() MobileIdentitiesProvider.collectSdkIdentifiers(event, api).also { sdkIdentitiesJson -> eventData[CONFIGURATION_RESPONSE_IDENTITY_ALL_IDENTIFIERS] = sdkIdentitiesJson } val responseIdentityEvent = Event.Builder( "Configuration Response Identity", EventType.CONFIGURATION, EventSource.RESPONSE_IDENTITY ).setEventData(eventData).inResponseToEvent(event).build() api.dispatch(responseIdentityEvent) } /** * Attempts to download the configuration associated with [appId] by dispatching * an internal configuration request event. * * @param appId the appId for which the config download should be attempted * @return the [Future] associated with the runnable that dispatches the configuration request event */ private fun retryConfigDownload(appId: String): Future<*> { val retryDelay = ++retryConfigurationCounter * CONFIG_DOWNLOAD_RETRY_ATTEMPT_DELAY_MS return retryWorker.schedule( { dispatchConfigurationRequest( mutableMapOf( CONFIGURATION_REQUEST_CONTENT_JSON_APP_ID to appId, CONFIGURATION_REQUEST_CONTENT_IS_INTERNAL_EVENT to true ) ) }, retryDelay, TimeUnit.MILLISECONDS ) } /** * Cancels the configuration retry attempt and resets the retry counter. */ private fun cancelConfigRetry() { retryConfigTaskHandle?.cancel(false) retryConfigTaskHandle = null retryConfigurationCounter = 0 } /** * Does three things * - Publishes the current configuration as configuration state * - Dispatches an event response broadly as a configuration response event * - Replaces current rules and applies the new rules based on [rulesSource] * * @param rulesSource the source of the rules that need to be applied * @param sharedStateResolver resolver to be notified with current state. * State will not be set if this is null. */ private fun applyConfigurationChanges( rulesSource: RulesSource, sharedStateResolver: SharedStateResolver? ) { val config = configurationStateManager.environmentAwareConfiguration sharedStateResolver?.resolve(config) dispatchConfigurationResponse(config) val rulesReplaced = replaceRules(rulesSource) if (rulesSource == RulesSource.CACHE && !rulesReplaced) { configurationRulesManager.applyBundledRules(api) } } /** * Dispatches a configuration response event in response to to [triggerEvent] * * @param eventData the content of the event data for the response event * @param triggerEvent the [Event] to which the response is being dispatched */ private fun dispatchConfigurationResponse( eventData: Map<String, Any?>, triggerEvent: Event? = null ) { val builder = Event.Builder( CoreConstants.EventNames.CONFIGURATION_RESPONSE, EventType.CONFIGURATION, EventSource.RESPONSE_CONTENT ).setEventData(eventData) val event: Event = if (triggerEvent == null) { builder.build() } else { builder.inResponseToEvent(triggerEvent).build() } api.dispatch(event) } private fun dispatchConfigurationRequest(eventData: Map<String, Any?>) { val event = Event.Builder( CoreConstants.EventNames.CONFIGURATION_REQUEST, EventType.CONFIGURATION, EventSource.REQUEST_CONTENT ) .setEventData(eventData).build() api.dispatch(event) } /** * Replaces the existing rules in the rules engine. * * @param rulesSource the source of the rules that need to be applied */ private fun replaceRules(rulesSource: RulesSource): Boolean { when (rulesSource) { RulesSource.CACHE -> { return configurationRulesManager.applyCachedRules(api) } RulesSource.BUNDLED -> { return configurationRulesManager.applyBundledRules(api) } RulesSource.REMOTE -> { val config = configurationStateManager.environmentAwareConfiguration val rulesURL: String? = config[RULES_CONFIG_URL] as? String return if (!rulesURL.isNullOrBlank()) { configurationRulesManager.applyDownloadedRules(rulesURL, api) } else { Log.debug( TAG, TAG, "Rules URL is empty or null" ) false } } } } /** * Determines if the current AppID update request is stale. * A request is considered stale if it is a configuration request sent internally * and there is a newer request that has been sent externally via {@link MobileCore#configureWithAppId(String)} * * @param newAppId the new app ID with which the configuration update is being requested * @param isInternalEvent whether the current request is an initial configuration request * @return true if the current request is stale, false otherwise */ private fun isStaleAppIdUpdateRequest(newAppId: String, isInternalEvent: Boolean): Boolean { // Because events are dispatched and processed serially, external config with app id events // cannot be stale. if (!isInternalEvent) return false // Load the currently persisted app id for validation val persistedAppId = appIdManager.getAppIDFromPersistence() return !persistedAppId.isNullOrBlank() && newAppId != persistedAppId } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/configuration/AppIdManager.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.configuration import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.NamedCollection import com.adobe.marketing.mobile.services.ServiceProvider /** * Manages the storage and retrieval of AEP appID from shared preferences and the app manifest. */ internal class AppIdManager { companion object { private const val LOG_TAG = "AppIdManager" } private val configStateStoreCollection: NamedCollection? = ServiceProvider.getInstance().dataStoreService .getNamedCollection(ConfigurationStateManager.DATASTORE_KEY) /** * Saves the appId provided into shared preferences. * * @param appId the appId to store/update to shared preferences */ internal fun saveAppIdToPersistence(appId: String) { if (appId.isBlank()) { Log.trace(ConfigurationExtension.TAG, LOG_TAG, "Attempting to set empty App Id into persistence.") return } configStateStoreCollection?.setString(ConfigurationStateManager.PERSISTED_APPID, appId) } /** * Removes the existing appId stored in shared preferences. */ internal fun removeAppIdFromPersistence() { Log.trace(ConfigurationExtension.TAG, LOG_TAG, "Attempting to set empty App Id into persistence.") configStateStoreCollection?.remove(ConfigurationStateManager.PERSISTED_APPID) } /** * Retrieves appId from persistence when available. Falls back to * retrieving it from manifest if nothing is persisted. * * @return the appId stored in manifest or persistence (in that order) if one exists; * null otherwise */ internal fun loadAppId(): String? { return getAppIDFromPersistence().also { persistedAppId -> persistedAppId?.let { Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Retrieved AppId from persistence." ) } } ?: getAppIDFromManifest().also { manifestAppId -> manifestAppId?.let { Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Retrieved AppId from manifest." ) saveAppIdToPersistence(it) } } } /** * Retrieves the existing appId stored in shared preferences. * * @return the existing appId stored in shared preferences if it exists, * null otherwise. */ internal fun getAppIDFromPersistence(): String? { return configStateStoreCollection?.getString( ConfigurationStateManager.PERSISTED_APPID, null ) } /** * Retrieves the existing appId from the manifest of the app. * * @return the existing appId from manifest if it exists, * null otherwise. */ private fun getAppIDFromManifest(): String? { return ServiceProvider.getInstance().deviceInfoService .getPropertyFromManifest(ConfigurationStateManager.CONFIG_MANIFEST_APPID_KEY) } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/configuration/ConfigurationRulesManager.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.configuration import androidx.annotation.VisibleForTesting import com.adobe.marketing.mobile.ExtensionApi import com.adobe.marketing.mobile.launch.rulesengine.LaunchRulesEngine import com.adobe.marketing.mobile.launch.rulesengine.download.RulesLoadResult import com.adobe.marketing.mobile.launch.rulesengine.download.RulesLoader import com.adobe.marketing.mobile.launch.rulesengine.json.JSONRulesParser import com.adobe.marketing.mobile.services.Log import com.adobe.marketing.mobile.services.NamedCollection import com.adobe.marketing.mobile.services.ServiceProvider /** * Facilitates notifying [LaunchRulesEvaluator] about replacing current rules with cached or newly * downloaded rules. */ internal class ConfigurationRulesManager { companion object { private const val LOG_TAG = "ConfigurationRulesManager" internal const val PERSISTED_RULES_URL = "config.last.rules.url" internal const val RULES_CACHE_NAME = "config.rules" internal const val BUNDLED_RULES_FILE_NAME = "ADBMobileConfig-rules.zip" } private val launchRulesEngine: LaunchRulesEngine private val rulesLoader: RulesLoader private val configDataStore: NamedCollection? constructor(launchRulesEngine: LaunchRulesEngine) : this( launchRulesEngine, RulesLoader(RULES_CACHE_NAME) ) @VisibleForTesting constructor(launchRulesEngine: LaunchRulesEngine, rulesLoader: RulesLoader) { this.launchRulesEngine = launchRulesEngine this.rulesLoader = rulesLoader configDataStore = ServiceProvider.getInstance().dataStoreService.getNamedCollection(ConfigurationExtension.DATASTORE_KEY) } /** * Replaces the rules with the ones cached locally. * * @return true if a rule replacement was triggered, false otherwise */ internal fun applyCachedRules(extensionApi: ExtensionApi): Boolean { if (configDataStore == null) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Cannot load rules from ${ConfigurationExtension.DATASTORE_KEY}. Cannot apply cached rules" ) return false } val persistedRulesUrl = configDataStore.getString(PERSISTED_RULES_URL, null) if (persistedRulesUrl.isNullOrBlank()) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Persisted rules url is null or empty. Cannot apply cached rules" ) return false } val rulesLoadResult: RulesLoadResult = rulesLoader.loadFromCache(persistedRulesUrl) if (rulesLoadResult.reason != RulesLoadResult.Reason.SUCCESS) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Cannot apply cached rules - ${rulesLoadResult.reason}" ) return false } Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Attempting to replace rules with cached rules" ) return replaceRules(rulesLoadResult.data, extensionApi) } /** * Replaces the rules after downloading them from a URL. * * @param url the URL from which the rules must be downloaded * @return true if a rule replacement was triggered, false otherwise */ internal fun applyDownloadedRules(url: String, extensionApi: ExtensionApi): Boolean { if (configDataStore == null) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Cannot load rules from ${ConfigurationExtension.DATASTORE_KEY}. Cannot apply downloaded rules" ) return false } configDataStore.setString(PERSISTED_RULES_URL, url) rulesLoader.loadFromUrl(url) { rulesDownloadResult -> val reason = rulesDownloadResult.reason Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Rule Download result: $reason" ) if (reason == RulesLoadResult.Reason.NOT_MODIFIED) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Rules from $url have not been modified. Will not apply rules." ) } else { Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Attempting to replace rules with downloaded rules." ) replaceRules(rulesDownloadResult.data, extensionApi) } } return true } /** * Loads and replaces the existing rules with ones from asset with name [BUNDLED_RULES_FILE_NAME] * * @return true if a rule replacement was triggered, false otherwise */ internal fun applyBundledRules(api: ExtensionApi): Boolean { val rulesLoadResult: RulesLoadResult = rulesLoader.loadFromAsset(BUNDLED_RULES_FILE_NAME) if (rulesLoadResult.reason != RulesLoadResult.Reason.SUCCESS) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Cannot apply bundled rules - ${rulesLoadResult.reason}" ) return false } Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Attempting to replace rules with bundled rules" ) return replaceRules(rulesLoadResult.data, api) } /** * Parses the rules from [rulesJson] and notifies [LaunchRulesEvaluator] * about the new rules. * * @param rulesJson the input json string from which rules must be parsed * @param extensionApi extensionApi * @return true if a rule replacement was triggered, false otherwise */ private fun replaceRules(rulesJson: String?, extensionApi: ExtensionApi): Boolean { if (rulesJson == null) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Rules file content is null. Cannot apply new rules." ) return false } val rules = JSONRulesParser.parse(rulesJson, extensionApi) return if (rules == null) { Log.debug( ConfigurationExtension.TAG, LOG_TAG, "Parsed rules are null. Cannot apply new rules." ) false } else { Log.trace( ConfigurationExtension.TAG, LOG_TAG, "Replacing rules." ) launchRulesEngine.replaceRules(rules) true } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/DatabaseProcessing.java
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util; import android.database.sqlite.SQLiteDatabase; import androidx.annotation.Nullable; @FunctionalInterface public interface DatabaseProcessing { /** * Performs the database operations with the {@link SQLiteDatabase} connection. * * @param database the (nullable) newly opened database * @return the result of the database operations. */ boolean execute(@Nullable final SQLiteDatabase database); }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/ActivityCompatOwner.kt
/* Copyright 2024 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util import android.app.Activity import android.view.View import androidx.activity.OnBackPressedDispatcher import androidx.activity.OnBackPressedDispatcherOwner import androidx.activity.setViewTreeOnBackPressedDispatcherOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.ViewModelStore import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.findViewTreeLifecycleOwner import androidx.lifecycle.setViewTreeLifecycleOwner import androidx.lifecycle.setViewTreeViewModelStoreOwner import androidx.savedstate.SavedStateRegistry import androidx.savedstate.SavedStateRegistryController import androidx.savedstate.SavedStateRegistryOwner import androidx.savedstate.setViewTreeSavedStateRegistryOwner /** * Utility class to attach and detach an [ActivityCompatOwner] to an activity. * Exists to mock and make tests easier to write for the calling component. * This component has to be manually tested due the internal threading and lifecycle management * of the Android SDK. */ internal class ActivityCompatOwnerUtils { /** * Attaches an [ActivityCompatOwner] to the given activity if it does not already have a lifecycle owner. * @param activityToAttach the activity to attach the [ActivityCompatOwner] to */ internal fun attachActivityCompatOwner(activityToAttach: Activity) { val decorView = activityToAttach.window.decorView if (decorView.findViewTreeLifecycleOwner() != null) { // If the activity already has a lifecycle owner, then we don't need to attach a new one return } val proxyLifeCycleOwner = ActivityCompatOwner() proxyLifeCycleOwner.onCreate() proxyLifeCycleOwner.attachToView(decorView) } /** * Detaches the [ActivityCompatOwner] from the given activity if it has one. * @param activityToDetach the activity to detach the [ActivityCompatOwner] from */ internal fun detachActivityCompatOwner(activityToDetach: Activity) { val decorView = activityToDetach.window.decorView // If the activity's lifecycle owner is not a ActivityCompatOwner, then there is nothing // to detach val lifecycleOwner = decorView.findViewTreeLifecycleOwner() if (lifecycleOwner !is ActivityCompatOwner) { return } lifecycleOwner.detachFromView(decorView) lifecycleOwner.onDestroy() } } /** * A proxy lifecycle owner that is used to attach to an activity's view tree to which a compose view * from the SDK is being attached. * This is required to provide a lifecycle owner to the view tree of an activity that inherits * from android.app.Activity which does not provide a lifecycle owner by default. Not doing so will * result in a crash when trying to attach a compose view. Android recommends using inheriting from * AppCompatActivity or similar which provides a lifecycle owner by default (irrespective of whether * compose is being used or not). This is a best effort to provide a lifecycle owner when this is not * the case. */ internal class ActivityCompatOwner : LifecycleOwner, ViewModelStoreOwner, SavedStateRegistryOwner, OnBackPressedDispatcherOwner { // LifecycleOwner methods private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this) override val lifecycle: Lifecycle get() = lifecycleRegistry // ViewModelStore methods private val store = ViewModelStore() override val viewModelStore: ViewModelStore get() = store // SavedStateRegistry methods private val savedStateRegistryController = SavedStateRegistryController.create(this) override val savedStateRegistry: SavedStateRegistry get() = savedStateRegistryController.savedStateRegistry // OnBackPressedDispatcherOwner methods private val dispatcher = OnBackPressedDispatcher {} override val onBackPressedDispatcher: OnBackPressedDispatcher get() = dispatcher /** * Trigger the ON_CREATE lifecycle event for this [ActivityCompatOwner]. */ internal fun onCreate() { savedStateRegistryController.performRestore(null) lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) } /** * Trigger the ON_DESTROY lifecycle event for this [ActivityCompatOwner]. */ internal fun onDestroy() { lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) store.clear() } /** * Attaches this [ActivityCompatOwner] to the given view. * @param view the view to attach this [ActivityCompatOwner] to */ internal fun attachToView(view: View?) { view?.apply { setViewTreeLifecycleOwner(this@ActivityCompatOwner) setViewTreeViewModelStoreOwner(this@ActivityCompatOwner) setViewTreeSavedStateRegistryOwner(this@ActivityCompatOwner) setViewTreeOnBackPressedDispatcherOwner(this@ActivityCompatOwner) } } /** * Detaches this [ActivityCompatOwner] from the given view. * @param view the view to detach this [ActivityCompatOwner] from */ internal fun detachFromView(view: View?) { view?.apply { setViewTreeLifecycleOwner(null) setViewTreeViewModelStoreOwner(null) setViewTreeSavedStateRegistryOwner(null) } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/MapExtensions.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util import com.adobe.marketing.mobile.internal.util.UrlEncoder.urlEncode import org.json.JSONObject /** * Convert map to a decimal FNV1a 32-bit hash. If a mask is provided, only use keys in the provided mask and alphabetize their order. * * @param masks contain keys to be hashed. * @return the decimal FNV1a 32-bit hash. */ @JvmSynthetic internal fun Map<String, Any?>.fnv1a32(masks: Array<String>? = null): Long { val flattenedMap = this.flattening() val kvPairs = StringBuilder() var innerMasks = masks if (innerMasks?.isEmpty() == true) innerMasks = null innerMasks?.let { it.sortedArray().forEach { mask -> if (mask.isNotEmpty() && !flattenedMap[mask].isNullOrEmptyString()) { kvPairs.append(mask).append(":").append(flattenedMap[mask].toString()) } } } ?: run { flattenedMap.toSortedMap().forEach { entry -> if (!entry.value.isNullOrEmptyString()) { kvPairs.append(entry.key).append(":").append(entry.value.toString()) } } } return StringEncoder.convertStringToDecimalHash(kvPairs.toString()) } /** * Flatten nested [Map]s and concatenate [String] keys * For example, an input [Map] of: * `[rootKey: [key1: value1, key2: value2]]` * will return a [Map] represented as: * `[rootKey.key1: value1, rootKey.key2: value2]` * * * @param prefix a prefix to append to the front of the key * @return flattened [Map] */ @JvmSynthetic internal fun Map<String, Any?>.flattening(prefix: String = ""): Map<String, Any?> { val keyPrefix = if (prefix.isNotEmpty()) "$prefix." else prefix val flattenedMap = mutableMapOf<String, Any?>() this.forEach { entry -> val expandedKey = keyPrefix + entry.key val value = entry.value if (value is Map<*, *> && value.keys.isAllString()) { @Suppress("UNCHECKED_CAST") flattenedMap.putAll((value as Map<String, Any?>).flattening(expandedKey)) } else { flattenedMap[expandedKey] = value } } return flattenedMap } /** * Serializes a map to key value pairs for url string. * This method is recursive to handle the nested data objects. * * @return resulted serialized query parameters as [String] */ @JvmSynthetic internal fun Map<String, Any?>.serializeToQueryString(): String { val builder = StringBuilder() for ((key, value) in this.entries) { val encodedKey = urlEncode(key) ?: continue // TODO add serializing for custom objects val encodedValue: String? = if (value is List<*>) { urlEncode(join(value, ",")) } else { urlEncode(value?.toString()) } val serializedKVP = serializeKeyValuePair(encodedKey, encodedValue) if (serializedKVP != null) { builder.append(serializedKVP) } } return if (builder.isNotEmpty()) builder.substring(1).toString() else builder.toString() } /** * Converts a map to a prettified JSON string * * @return map as json string */ internal fun Map<String, Any?>.prettify(): String { return try { JSONObject(this).toString(4) } catch (e: Exception) { return this.toString() } } /** * Encodes the key/value pair and prepares it in the URL format. * If the value is a List, it will create a join string with the "," delimiter before encoding, * otherwise it will use toString method on other objects. * * @param key the string value that we want to append to the builder * @param value the object value that we want to encode and append to the builder * @return [String] containing key/value pair encoded in URL format */ private fun serializeKeyValuePair(key: String?, value: String?): String? { if (key.isNullOrBlank() || value == null) { return null } return "&$key=$value" } /** * Returns a [String] containing the elements joined by delimiters. * * @param elements an array objects to be joined. A [String] will be formed from the objects * by calling object.toString(). * @param delimiter the `String` to be used as the delimiter between all elements * @return [String] containing the elements joined by delimiters */ private fun join(elements: Iterable<*>, delimiter: String): String { return elements.joinToString(delimiter) } /** * Returns a [Boolean] containing true if the value is null or an empty [String], false otherwise. * * @return [Boolean] true if the value is null or an empty [String], false otherwise */ private fun Any?.isNullOrEmptyString(): Boolean = this == null || (this is String && this.isEmpty())
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/MapUtils.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util /** * Convert map to a decimal FNV1a 32-bit hash. If a mask is provided, only use keys in the provided mask and alphabetize their order. * * @param map the [Map] to be converted to FNV1a 32-bit hash * @param masks contain keys to be hashed. * @return the decimal FNV1a 32-bit hash. */ internal fun convertMapToFnv1aHash(map: Map<String, Any?>?, masks: Array<String>?): Long { return map?.fnv1a32(masks) ?: -1 }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/EventDataMerger.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util internal object EventDataMerger { private const val WILD_CARD_SUFFIX_FOR_LIST = "[*]" /** * Merge one [Map] into another * * @param from the map containing new data * @param to the map to be merged to * @param overwrite true, if the from map should take priority * @return the merged [Map] */ @JvmStatic fun merge( from: Map<String, Any?>?, to: Map<String, Any?>?, overwrite: Boolean ): Map<String, Any?> { return innerMerge( from, to, overwrite, fun(fromValue, toValue): Any? { if (fromValue is Map<*, *> && toValue is Map<*, *>) { return mergeWildcardMaps(fromValue, toValue, overwrite) } if (!overwrite) { return toValue } if (fromValue is Collection<*> && toValue is Collection<*>) { return mergeCollection(fromValue, toValue) } return fromValue } ) } private fun mergeCollection(from: Collection<*>?, to: Collection<*>?): Collection<Any?> { return object : ArrayList<Any?>() { init { from?.let { addAll(it) } to?.let { addAll(it) } } } } @Suppress("UNCHECKED_CAST") private fun mergeWildcardMaps( from: Map<*, *>?, to: Map<*, *>?, overwrite: Boolean ): Map<*, *>? { from?.let { if (!it.keys.isAllString()) return to } to?.let { if (!it.keys.isAllString()) return to } return try { merge(from as? Map<String, Any?>, to as? Map<String, Any?>, overwrite) } catch (e: Exception) { to } } private fun innerMerge( from: Map<String, Any?>?, to: Map<String, Any?>?, overwrite: Boolean, overwriteStrategy: (fromValue: Any?, toValue: Any?) -> Any? ): Map<String, Any?> { val mergedMap = HashMap<String, Any?>() to?.let(mergedMap::putAll) from?.forEach { (k, v) -> when { mergedMap.containsKey(k) -> { val resolvedValue = overwriteStrategy(v, mergedMap[k]) resolvedValue?.let { mergedMap[k] = resolvedValue } ?: mergedMap.remove(k) } k.endsWith(WILD_CARD_SUFFIX_FOR_LIST) -> { if (v is Map<*, *>) handleWildcardMerge(mergedMap, k, v, overwrite) } else -> { mergedMap[k] = v } } } return mergedMap } /** * If the map contains the specific key and its value is a [Collection], merge `data` to each item of the [Collection] * * For example: * for the wildcard key: `list[*]`, merge the following data: * {"k":"v"} * to the target [Map]: * {"list":[{"k1":"v1"},{"k2":"v2"}]} * the result is: * {"list":[{"k1":"v1","k":"v"},{"k2":"v2","k":"v"}]} * * @param targetMap the [Map] to be merged with the given `data` if it contains the target key * @param wildcardKey the target key with suffix `[*]` * @param data the new data to be merged to the `targetMap` * @param overwrite true, if the new data should take priority */ private fun handleWildcardMerge( targetMap: HashMap<String, Any?>, wildcardKey: String, data: Map<*, *>, overwrite: Boolean ) { val targetKey = wildcardKey.dropLast(WILD_CARD_SUFFIX_FOR_LIST.length) val targetValueAsList = targetMap[targetKey] if (targetValueAsList is Collection<*>) { val newList = ArrayList<Any?>() targetValueAsList.forEach { val itMap = it as? Map<*, *> itMap?.let { newList.add(mergeWildcardMaps(data, itMap, overwrite)) } ?: run { newList.add(it) } } targetMap[targetKey] = newList } } }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/JSONExtensions.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util import org.json.JSONArray import org.json.JSONObject /** * Returns a list containing the results of applying the given [transform] function * to each element in the [JSONArray]. * */ @JvmSynthetic internal fun <T> JSONArray.map(transform: (Any) -> T): List<T> { return (0 until this.length()).asSequence().map { transform(this.get(it)) }.toList() } /** * Converts the [JSONObject] to a map of the contained contents. * */ @JvmSynthetic internal fun JSONObject.toMap(): Map<String, Any?> { return this.keys().asSequence().associateWith { key -> when (val value = this.get(key)) { is JSONObject -> { value.toMap() } is JSONArray -> { value.toList() } JSONObject.NULL -> null else -> value } } } /** * Converts the [JSONArray] to a list of the contained contents, * the list could contains [JSONObject], [JSONArray], `null` or the `primitive types`. * */ @JvmSynthetic internal fun JSONArray.toList(): List<Any?> { val list = mutableListOf<Any?>() (0 until this.length()).forEach { index -> when (val value = this.get(index)) { is JSONObject -> { list.add(value.toMap()) } is JSONArray -> { list.add(value.toList()) } JSONObject.NULL -> list.add(null) else -> list.add(value) } } return list }
0
AEP Core
/Users/yy/GIT/Github/llm-fine-tune/data_prep/repos/core_3_2_0/core/src/main/java/com/adobe/marketing/mobile/internal/util/SetExtensions.kt
/* Copyright 2022 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.marketing.mobile.internal.util internal fun Set<*>.isAllString(): Boolean { return isNotEmpty() && all { it is String } }
0