index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile
java-sources/ai/themsp/prebid-core/2.0.3.30/main/org/prebid/mobile/tasksmanager/TasksManager.java
/* * Copyright 2020-2021 Prebid.org, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.prebid.mobile.tasksmanager; import java.util.concurrent.Executor; public class TasksManager { private static TasksManager instance = null; public Executor mainThreadExecutor; public Executor backgroundThreadExecutor; private TasksManager() { mainThreadExecutor = new MainThreadExecutor(); backgroundThreadExecutor = new BackgroundThreadExecutor(); } /** * Factory method to obtain the Singleton instance of the TasksManager * */ public synchronized static TasksManager getInstance() { if (instance == null) { synchronized (TasksManager.class) { instance = new TasksManager(); } } return instance; } /** * This API can be used to execute code block on the main thread. * @param task takes in task (to be executed on main thread) as a runnable * */ public void executeOnMainThread(Runnable task) { mainThreadExecutor.execute(task); } /** * Utility method to cancel an ongoing main thread task * @param task takes in task to be cancelled * */ public void cancelTaskOnMainThread(Runnable task) { ((CancellableExecutor) mainThreadExecutor).cancel(task); } /** * This API can be used to execute code block on the background thread. * @param task takes in task (to be executed on background thread) as a runnable * */ public void executeOnBackgroundThread(Runnable task) { backgroundThreadExecutor.execute(task); } /** * Utility method to cancel an ongoing background thread task * @param task takes in task to be cancelled * */ public void cancelTaksOnBackgroundThread(Runnable task) { ((CancellableExecutor) backgroundThreadExecutor).cancel(task); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/ApiCallback.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch; import java.io.IOException; import java.util.Map; import java.util.List; /** * Callback for asynchronous API call. * * @param <T> The return type */ public interface ApiCallback<T> { /** * This is called when the API call fails. * * @param e The exception causing the failure * @param statusCode Status code of the response if available, otherwise it would be 0 * @param responseHeaders Headers of the response if available, otherwise it would be null */ void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders); /** * This is called when the API call succeeded. * * @param result The result deserialized from response * @param statusCode Status code of the response * @param responseHeaders Headers of the response */ void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders); /** * This is called when the API upload processing. * * @param bytesWritten bytes Written * @param contentLength content length of request body * @param done write end */ void onUploadProgress(long bytesWritten, long contentLength, boolean done); /** * This is called when the API downlond processing. * * @param bytesRead bytes Read * @param contentLength content lenngth of the response * @param done Read end */ void onDownloadProgress(long bytesRead, long contentLength, boolean done); }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/ApiClient.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.MultipartBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.Headers; import com.squareup.okhttp.internal.http.HttpMethod; import com.squareup.okhttp.logging.HttpLoggingInterceptor; import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; import java.lang.reflect.Type; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.net.URLEncoder; import java.net.URLConnection; import java.io.File; import java.io.InputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import okio.BufferedSink; import okio.Okio; import ai.thirdwatch.auth.Authentication; import ai.thirdwatch.auth.HttpBasicAuth; import ai.thirdwatch.auth.ApiKeyAuth; import ai.thirdwatch.auth.OAuth; public class ApiClient { public static final double JAVA_VERSION; public static final boolean IS_ANDROID; public static final int ANDROID_SDK_VERSION; static { JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version")); boolean isAndroid; try { Class.forName("android.app.Activity"); isAndroid = true; } catch (ClassNotFoundException e) { isAndroid = false; } IS_ANDROID = isAndroid; int sdkVersion = 0; if (IS_ANDROID) { try { sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null); } catch (Exception e) { try { sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null)); } catch (Exception e2) { } } } ANDROID_SDK_VERSION = sdkVersion; } /** * The datetime format to be used when <code>lenientDatetimeFormat</code> is enabled. */ public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; private String basePath = "http://api.thirdwatch.co/event"; private boolean lenientOnJson = false; private boolean debugging = false; private Map<String, String> defaultHeaderMap = new HashMap<String, String>(); private String tempFolderPath = null; private Map<String, Authentication> authentications; private DateFormat dateFormat; private DateFormat datetimeFormat; private boolean lenientDatetimeFormat; private int dateLength; private InputStream sslCaCert; private boolean verifyingSsl; private KeyManager[] keyManagers; private OkHttpClient httpClient; private JSON json; private HttpLoggingInterceptor loggingInterceptor; /* * Constructor for ApiClient */ public ApiClient() { httpClient = new OkHttpClient(); verifyingSsl = true; json = new JSON(this); /* * Use RFC3339 format for date and datetime. * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 */ this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // Always use UTC as the default time zone when dealing with date (without time). this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); initDatetimeFormat(); // Be lenient on datetime formats when parsing datetime from string. // See <code>parseDatetime</code>. this.lenientDatetimeFormat = true; // Set default User-Agent. setUserAgent("Swagger-Codegen/0.0.1/java"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap<String, Authentication>(); authentications.put("api_key", new ApiKeyAuth("header", "X-THIRDWATCH-API-KEY")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } /** * Get base path * * @return Baes path */ public String getBasePath() { return basePath; } /** * Set base path * * @param basePath Base path of the URL (e.g https://localhost/event * @return An instance of OkHttpClient */ public ApiClient setBasePath(String basePath) { this.basePath = basePath; return this; } /** * Get HTTP client * * @return An instance of OkHttpClient */ public OkHttpClient getHttpClient() { return httpClient; } /** * Set HTTP client * * @param httpClient An instance of OkHttpClient * @return Api Client */ public ApiClient setHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Get JSON * * @return JSON object */ public JSON getJSON() { return json; } /** * Set JSON * * @param json JSON object * @return Api client */ public ApiClient setJSON(JSON json) { this.json = json; return this; } /** * True if isVerifyingSsl flag is on * * @return True if isVerifySsl flag is on */ public boolean isVerifyingSsl() { return verifyingSsl; } /** * Configure whether to verify certificate and hostname when making https requests. * Default to true. * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. * * @param verifyingSsl True to verify TLS/SSL connection * @return ApiClient */ public ApiClient setVerifyingSsl(boolean verifyingSsl) { this.verifyingSsl = verifyingSsl; applySslSettings(); return this; } /** * Get SSL CA cert. * * @return Input stream to the SSL CA cert */ public InputStream getSslCaCert() { return sslCaCert; } /** * Configure the CA certificate to be trusted when making https requests. * Use null to reset to default. * * @param sslCaCert input stream for SSL CA cert * @return ApiClient */ public ApiClient setSslCaCert(InputStream sslCaCert) { this.sslCaCert = sslCaCert; applySslSettings(); return this; } public KeyManager[] getKeyManagers() { return keyManagers; } /** * Configure client keys to use for authorization in an SSL session. * Use null to reset to default. * * @param managers The KeyManagers to use * @return ApiClient */ public ApiClient setKeyManagers(KeyManager[] managers) { this.keyManagers = managers; applySslSettings(); return this; } public DateFormat getDateFormat() { return dateFormat; } public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; this.dateLength = this.dateFormat.format(new Date()).length(); return this; } public DateFormat getDatetimeFormat() { return datetimeFormat; } public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { this.datetimeFormat = datetimeFormat; return this; } /** * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. * @see #parseDatetime(String) * @return True if lenientDatetimeFormat flag is set to true */ public boolean isLenientDatetimeFormat() { return lenientDatetimeFormat; } public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { this.lenientDatetimeFormat = lenientDatetimeFormat; return this; } /** * Parse the given date string into Date object. * The default <code>dateFormat</code> supports these ISO 8601 date formats: * 2015-08-16 * 2015-8-16 * @param str String to be parsed * @return Date */ public Date parseDate(String str) { if (str == null) return null; try { return dateFormat.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } } /** * Parse the given datetime string into Date object. * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: * 2015-08-16T08:20:05Z * 2015-8-16T8:20:05Z * 2015-08-16T08:20:05+00:00 * 2015-08-16T08:20:05+0000 * 2015-08-16T08:20:05.376Z * 2015-08-16T08:20:05.376+00:00 * 2015-08-16T08:20:05.376+00 * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of * these formats: * Z (same with +0000) * +08:00 (same with +0800) * -02 (same with -0200) * -0200 * @see <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> * @param str Date time string to be parsed * @return Date representation of the string */ public Date parseDatetime(String str) { if (str == null) return null; DateFormat format; if (lenientDatetimeFormat) { /* * When lenientDatetimeFormat is enabled, normalize the date string * into <code>LENIENT_DATETIME_FORMAT</code> to support various formats * defined by ISO 8601. */ // normalize time zone // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 str = str.replaceAll("[zZ]\\z", "+0000"); // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 str = str.replaceAll("([+-]\\d{2})\\z", "$100"); // add milliseconds when missing // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT); } else { format = this.datetimeFormat; } try { return format.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } } /* * Parse date or date time in string format into Date object. * * @param str Date time string to be parsed * @return Date representation of the string */ public Date parseDateOrDatetime(String str) { if (str == null) return null; else if (str.length() <= dateLength) return parseDate(str); else return parseDatetime(str); } /** * Format the given Date object into string (Date format). * * @param date Date object * @return Formatted date in string representation */ public String formatDate(Date date) { return dateFormat.format(date); } /** * Format the given Date object into string (Datetime format). * * @param date Date object * @return Formatted datetime in string representation */ public String formatDatetime(Date date) { return datetimeFormat.format(date); } /** * Get authentications (key: authentication name, value: authentication). * * @return Map of authentication objects */ public Map<String, Authentication> getAuthentications() { return authentications; } /** * Get authentication for the given name. * * @param authName The authentication name * @return The authentication, null if not found */ public Authentication getAuthentication(String authName) { return authentications.get(authName); } /** * Helper method to set username for the first HTTP basic authentication. * * @param username Username */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setUsername(username); return; } } throw new RuntimeException("No HTTP basic authentication configured!"); } /** * Helper method to set password for the first HTTP basic authentication. * * @param password Password */ public void setPassword(String password) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { ((HttpBasicAuth) auth).setPassword(password); return; } } throw new RuntimeException("No HTTP basic authentication configured!"); } /** * Helper method to set API key value for the first API key authentication. * * @param apiKey API key */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { ((ApiKeyAuth) auth).setApiKey(apiKey); return; } } throw new RuntimeException("No API key authentication configured!"); } /** * Helper method to set API key prefix for the first API key authentication. * * @param apiKeyPrefix API key prefix */ public void setApiKeyPrefix(String apiKeyPrefix) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); return; } } throw new RuntimeException("No API key authentication configured!"); } /** * Helper method to set access token for the first OAuth2 authentication. * * @param accessToken Access token */ public void setAccessToken(String accessToken) { for (Authentication auth : authentications.values()) { if (auth instanceof OAuth) { ((OAuth) auth).setAccessToken(accessToken); return; } } throw new RuntimeException("No OAuth2 authentication configured!"); } /** * Set the User-Agent header's value (by adding to the default header map). * * @param userAgent HTTP request's user agent * @return ApiClient */ public ApiClient setUserAgent(String userAgent) { addDefaultHeader("User-Agent", userAgent); return this; } /** * Add a default header. * * @param key The header's key * @param value The header's value * @return ApiClient */ public ApiClient addDefaultHeader(String key, String value) { defaultHeaderMap.put(key, value); return this; } /** * @see <a href="https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)">setLenient</a> * * @return True if lenientOnJson is enabled, false otherwise. */ public boolean isLenientOnJson() { return lenientOnJson; } /** * Set LenientOnJson * * @param lenient True to enable lenientOnJson * @return ApiClient */ public ApiClient setLenientOnJson(boolean lenient) { this.lenientOnJson = lenient; return this; } /** * Check that whether debugging is enabled for this API client. * * @return True if debugging is enabled, false otherwise. */ public boolean isDebugging() { return debugging; } /** * Enable/disable debugging for this API client. * * @param debugging To enable (true) or disable (false) debugging * @return ApiClient */ public ApiClient setDebugging(boolean debugging) { if (debugging != this.debugging) { if (debugging) { loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(Level.BODY); httpClient.interceptors().add(loggingInterceptor); } else { httpClient.interceptors().remove(loggingInterceptor); loggingInterceptor = null; } } this.debugging = debugging; return this; } /** * The path of temporary folder used to store downloaded files from endpoints * with file response. The default value is <code>null</code>, i.e. using * the system's default tempopary folder. * * @see <a href="https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile">createTempFile</a> * @return Temporary folder path */ public String getTempFolderPath() { return tempFolderPath; } /** * Set the tempoaray folder path (for downloading files) * * @param tempFolderPath Temporary folder path * @return ApiClient */ public ApiClient setTempFolderPath(String tempFolderPath) { this.tempFolderPath = tempFolderPath; return this; } /** * Get connection timeout (in milliseconds). * * @return Timeout in milliseconds */ public int getConnectTimeout() { return httpClient.getConnectTimeout(); } /** * Sets the connect timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and * * @param connectionTimeout connection timeout in milliseconds * @return Api client */ public ApiClient setConnectTimeout(int connectionTimeout) { httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS); return this; } /** * Format the given parameter object into string. * * @param param Parameter * @return String representation of the parameter */ public String parameterToString(Object param) { if (param == null) { return ""; } else if (param instanceof Date) { return formatDatetime((Date) param); } else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); for (Object o : (Collection)param) { if (b.length() > 0) { b.append(","); } b.append(String.valueOf(o)); } return b.toString(); } else { return String.valueOf(param); } } /** * Format to {@code Pair} objects. * * @param collectionFormat collection format (e.g. csv, tsv) * @param name Name * @param value Value * @return A list of Pair objects */ public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){ List<Pair> params = new ArrayList<Pair>(); // preconditions if (name == null || name.isEmpty() || value == null) return params; Collection valueCollection = null; if (value instanceof Collection) { valueCollection = (Collection) value; } else { params.add(new Pair(name, parameterToString(value))); return params; } if (valueCollection.isEmpty()){ return params; } // get the collection format collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv // create the params based on the collection format if (collectionFormat.equals("multi")) { for (Object item : valueCollection) { params.add(new Pair(name, parameterToString(item))); } return params; } String delimiter = ","; if (collectionFormat.equals("csv")) { delimiter = ","; } else if (collectionFormat.equals("ssv")) { delimiter = " "; } else if (collectionFormat.equals("tsv")) { delimiter = "\t"; } else if (collectionFormat.equals("pipes")) { delimiter = "|"; } StringBuilder sb = new StringBuilder() ; for (Object item : valueCollection) { sb.append(delimiter); sb.append(parameterToString(item)); } params.add(new Pair(name, sb.substring(1))); return params; } /** * Sanitize filename by removing path. * e.g. ../../sun.gif becomes sun.gif * * @param filename The filename to be sanitized * @return The sanitized filename */ public String sanitizeFilename(String filename) { return filename.replaceAll(".*[/\\\\]", ""); } /** * Check if the given MIME is a JSON MIME. * JSON MIME examples: * application/json * application/json; charset=UTF8 * APPLICATION/JSON * application/vnd.company+json * @param mime MIME (Multipurpose Internet Mail Extensions) * @return True if the given MIME is JSON, false otherwise. */ public boolean isJsonMime(String mime) { String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; return mime != null && (mime.matches(jsonMime) || mime.equalsIgnoreCase("application/json-patch+json")); } /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; * otherwise use all of them (joining into a string) * * @param accepts The accepts array to select from * @return The Accept header to use. If the given array is empty, * null will be returned (not to set the Accept header explicitly). */ public String selectHeaderAccept(String[] accepts) { if (accepts.length == 0) { return null; } for (String accept : accepts) { if (isJsonMime(accept)) { return accept; } } return StringUtil.join(accepts, ","); } /** * Select the Content-Type header's value from the given array: * if JSON exists in the given array, use it; * otherwise use the first one of the array. * * @param contentTypes The Content-Type array to select from * @return The Content-Type header to use. If the given array is empty, * JSON will be used. */ public String selectHeaderContentType(String[] contentTypes) { if (contentTypes.length == 0) { return "application/json"; } for (String contentType : contentTypes) { if (isJsonMime(contentType)) { return contentType; } } return contentTypes[0]; } /** * Escape the given string to be used as URL query value. * * @param str String to be escaped * @return Escaped string */ public String escapeString(String str) { try { return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException e) { return str; } } /** * Deserialize response body to Java object, according to the return type and * the Content-Type response header. * * @param <T> Type * @param response HTTP response * @param returnType The type of the Java object * @return The deserialized Java object * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ @SuppressWarnings("unchecked") public <T> T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; } if ("byte[]".equals(returnType.toString())) { // Handle binary response (byte array). try { return (T) response.body().bytes(); } catch (IOException e) { throw new ApiException(e); } } else if (returnType.equals(File.class)) { // Handle file downloading. return (T) downloadFileFromResponse(response); } String respBody; try { if (response.body() != null) respBody = response.body().string(); else respBody = null; } catch (IOException e) { throw new ApiException(e); } if (respBody == null || "".equals(respBody)) { return null; } String contentType = response.headers().get("Content-Type"); if (contentType == null) { // ensuring a default content type contentType = "application/json"; } if (isJsonMime(contentType)) { return json.deserialize(respBody, returnType); } else if (returnType.equals(String.class)) { // Expecting string, return the raw response body. return (T) respBody; } else { throw new ApiException( "Content type \"" + contentType + "\" is not supported for type: " + returnType, response.code(), response.headers().toMultimap(), respBody); } } /** * Serialize the given Java object into request body according to the object's * class and the request Content-Type. * * @param obj The Java object * @param contentType The request Content-Type * @return The serialized request body * @throws ApiException If fail to serialize the given object */ public RequestBody serialize(Object obj, String contentType) throws ApiException { if (obj instanceof byte[]) { // Binary (byte array) body parameter support. return RequestBody.create(MediaType.parse(contentType), (byte[]) obj); } else if (obj instanceof File) { // File body parameter support. return RequestBody.create(MediaType.parse(contentType), (File) obj); } else if (isJsonMime(contentType)) { String content; if (obj != null) { content = json.serialize(obj); } else { content = null; } return RequestBody.create(MediaType.parse(contentType), content); } else { throw new ApiException("Content type \"" + contentType + "\" is not supported"); } } /** * Download file from the given response. * * @param response An instance of the Response object * @throws ApiException If fail to read file content from response and write to disk * @return Downloaded file */ public File downloadFileFromResponse(Response response) throws ApiException { try { File file = prepareDownloadFile(response); BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(response.body().source()); sink.close(); return file; } catch (IOException e) { throw new ApiException(e); } } /** * Prepare file for download * * @param response An instance of the Response object * @throws IOException If fail to prepare file for download * @return Prepared file for the download */ public File prepareDownloadFile(Response response) throws IOException { String filename = null; String contentDisposition = response.header("Content-Disposition"); if (contentDisposition != null && !"".equals(contentDisposition)) { // Get filename from the Content-Disposition header. Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); Matcher matcher = pattern.matcher(contentDisposition); if (matcher.find()) { filename = sanitizeFilename(matcher.group(1)); } } String prefix = null; String suffix = null; if (filename == null) { prefix = "download-"; suffix = ""; } else { int pos = filename.lastIndexOf("."); if (pos == -1) { prefix = filename + "-"; } else { prefix = filename.substring(0, pos) + "-"; suffix = filename.substring(pos); } // File.createTempFile requires the prefix to be at least three characters long if (prefix.length() < 3) prefix = "download-"; } if (tempFolderPath == null) return File.createTempFile(prefix, suffix); else return File.createTempFile(prefix, suffix, new File(tempFolderPath)); } /** * {@link #execute(Call, Type)} * * @param <T> Type * @param call An instance of the Call object * @throws ApiException If fail to execute the call * @return ApiResponse&lt;T&gt; */ public <T> ApiResponse<T> execute(Call call) throws ApiException { return execute(call, null); } /** * Execute HTTP call and deserialize the HTTP response body into the given return type. * * @param returnType The return type used to deserialize HTTP response body * @param <T> The return type corresponding to (same with) returnType * @param call Call * @return ApiResponse object containing response status, headers and * data, which is a Java object deserialized from response body and would be null * when returnType is null. * @throws ApiException If fail to execute the call */ public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException { try { Response response = call.execute(); T data = handleResponse(response, returnType); return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data); } catch (IOException e) { throw new ApiException(e); } } /** * {@link #executeAsync(Call, Type, ApiCallback)} * * @param <T> Type * @param call An instance of the Call object * @param callback ApiCallback&lt;T&gt; */ public <T> void executeAsync(Call call, ApiCallback<T> callback) { executeAsync(call, null, callback); } /** * Execute HTTP call asynchronously. * * @see #execute(Call, Type) * @param <T> Type * @param call The callback to be executed when the API call finishes * @param returnType Return type * @param callback ApiCallback */ @SuppressWarnings("unchecked") public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) { call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { callback.onFailure(new ApiException(e), 0, null); } @Override public void onResponse(Response response) throws IOException { T result; try { result = (T) handleResponse(response, returnType); } catch (ApiException e) { callback.onFailure(e, response.code(), response.headers().toMultimap()); return; } callback.onSuccess(result, response.code(), response.headers().toMultimap()); } }); } /** * Handle the given response, return the deserialized object when the response is successful. * * @param <T> Type * @param response Response * @param returnType Return type * @throws ApiException If the response has a unsuccessful status code or * fail to deserialize the response body * @return Type */ public <T> T handleResponse(Response response, Type returnType) throws ApiException { if (response.isSuccessful()) { if (returnType == null || response.code() == 204) { // returning null if the returnType is not defined, // or the status code is 204 (No Content) if (response.body() != null) { try { response.body().close(); } catch (IOException e) { throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); } } return null; } else { return deserialize(response, returnType); } } else { String respBody = null; if (response.body() != null) { try { respBody = response.body().string(); } catch (IOException e) { throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); } } throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); } } /** * Build HTTP call with the given options. * * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param body The request body object * @param headerParams The header parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param progressRequestListener Progress request listener * @return The HTTP call * @throws ApiException If fail to serialize the request body object */ public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Request request = buildRequest(path, method, queryParams, body, headerParams, formParams, authNames, progressRequestListener); return httpClient.newCall(request); } /** * Build an HTTP request with the given options. * * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param body The request body object * @param headerParams The header parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param progressRequestListener Progress request listener * @return The HTTP request * @throws ApiException If fail to serialize the request body object */ public Request buildRequest(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); final String url = buildUrl(path, queryParams); final Request.Builder reqBuilder = new Request.Builder().url(url); processHeaderParams(headerParams, reqBuilder); String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type if (contentType == null) { contentType = "application/json"; } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentType)) { reqBody = buildRequestBodyMultipart(formParams); } else if (body == null) { if ("DELETE".equals(method)) { // allow calling DELETE without sending a request body reqBody = null; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { reqBody = serialize(body, contentType); } Request request = null; if(progressRequestListener != null && reqBody != null) { ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); request = reqBuilder.method(method, progressRequestBody).build(); } else { request = reqBuilder.method(method, reqBody).build(); } return request; } /** * Build full URL by concatenating base path, the given sub path and query parameters. * * @param path The sub path * @param queryParams The query parameters * @return The full URL */ public String buildUrl(String path, List<Pair> queryParams) { final StringBuilder url = new StringBuilder(); url.append(basePath).append(path); if (queryParams != null && !queryParams.isEmpty()) { // support (constant) query string in `path`, e.g. "/posts?draft=1" String prefix = path.contains("?") ? "&" : "?"; for (Pair param : queryParams) { if (param.getValue() != null) { if (prefix != null) { url.append(prefix); prefix = null; } else { url.append("&"); } String value = parameterToString(param.getValue()); url.append(escapeString(param.getName())).append("=").append(escapeString(value)); } } } return url.toString(); } /** * Set header parameters to the request builder, including default headers. * * @param headerParams Header parameters in the ofrm of Map * @param reqBuilder Reqeust.Builder */ public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) { for (Entry<String, String> param : headerParams.entrySet()) { reqBuilder.header(param.getKey(), parameterToString(param.getValue())); } for (Entry<String, String> header : defaultHeaderMap.entrySet()) { if (!headerParams.containsKey(header.getKey())) { reqBuilder.header(header.getKey(), parameterToString(header.getValue())); } } } /** * Update query and header parameters based on authentication settings. * * @param authNames The authentications to apply * @param queryParams List of query parameters * @param headerParams Map of header parameters */ public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); auth.applyToParams(queryParams, headerParams); } } /** * Build a form-encoding request body with the given form parameters. * * @param formParams Form parameters in the form of Map * @return RequestBody */ public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) { FormEncodingBuilder formBuilder = new FormEncodingBuilder(); for (Entry<String, Object> param : formParams.entrySet()) { formBuilder.add(param.getKey(), parameterToString(param.getValue())); } return formBuilder.build(); } /** * Build a multipart (file uploading) request body with the given form parameters, * which could contain text fields and file fields. * * @param formParams Form parameters in the form of Map * @return RequestBody */ public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) { MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); for (Entry<String, Object> param : formParams.entrySet()) { if (param.getValue() instanceof File) { File file = (File) param.getValue(); Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); } else { Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); } } return mpBuilder.build(); } /** * Guess Content-Type header from the given file (defaults to "application/octet-stream"). * * @param file The given file * @return The guessed Content-Type */ public String guessContentTypeFromFile(File file) { String contentType = URLConnection.guessContentTypeFromName(file.getName()); if (contentType == null) { return "application/octet-stream"; } else { return contentType; } } /** * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android. */ private void initDatetimeFormat() { String formatWithTimeZone = null; if (IS_ANDROID) { if (ANDROID_SDK_VERSION >= 18) { // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18) formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; } } else if (JAVA_VERSION >= 1.7) { // The time zone format "XXX" is available since Java 1.7 formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; } if (formatWithTimeZone != null) { this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone); // NOTE: Use the system's default time zone (mainly for datetime formatting). } else { // Use a common format that works across all systems. this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Always use the UTC time zone as we are using a constant trailing "Z" here. this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } } /** * Apply SSL related settings to httpClient according to the current values of * verifyingSsl and sslCaCert. */ private void applySslSettings() { try { TrustManager[] trustManagers = null; HostnameVerifier hostnameVerifier = null; if (!verifyingSsl) { TrustManager trustAll = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslContext = SSLContext.getInstance("TLS"); trustManagers = new TrustManager[]{ trustAll }; hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; } else if (sslCaCert != null) { char[] password = null; // Any password will work. CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert); if (certificates.isEmpty()) { throw new IllegalArgumentException("expected non-empty set of trusted certificates"); } KeyStore caKeyStore = newEmptyKeyStore(password); int index = 0; for (Certificate certificate : certificates) { String certificateAlias = "ca" + Integer.toString(index++); caKeyStore.setCertificateEntry(certificateAlias, certificate); } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(caKeyStore); trustManagers = trustManagerFactory.getTrustManagers(); } if (keyManagers != null || trustManagers != null) { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, new SecureRandom()); httpClient.setSslSocketFactory(sslContext.getSocketFactory()); } else { httpClient.setSslSocketFactory(null); } httpClient.setHostnameVerifier(hostnameVerifier); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, password); return keyStore; } catch (IOException e) { throw new AssertionError(e); } } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/ApiException.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch; import java.util.Map; import java.util.List; @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class ApiException extends Exception { private int code = 0; private Map<String, List<String>> responseHeaders = null; private String responseBody = null; public ApiException() {} public ApiException(Throwable throwable) { super(throwable); } public ApiException(String message) { super(message); } public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) { super(message, throwable); this.code = code; this.responseHeaders = responseHeaders; this.responseBody = responseBody; } public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) { this(message, (Throwable) null, code, responseHeaders, responseBody); } public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) { this(message, throwable, code, responseHeaders, null); } public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) { this((String) null, (Throwable) null, code, responseHeaders, responseBody); } public ApiException(int code, String message) { super(message); this.code = code; } public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) { this(code, message); this.responseHeaders = responseHeaders; this.responseBody = responseBody; } /** * Get the HTTP status code. * * @return HTTP status code */ public int getCode() { return code; } /** * Get the HTTP response headers. * * @return A map of list of string */ public Map<String, List<String>> getResponseHeaders() { return responseHeaders; } /** * Get the HTTP response body. * * @return Response body in the form of string */ public String getResponseBody() { return responseBody; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/ApiResponse.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch; import java.util.List; import java.util.Map; /** * API response returned by API call. * * @param <T> The type of data that is deserialized from response body */ public class ApiResponse<T> { final private int statusCode; final private Map<String, List<String>> headers; final private T data; /** * @param statusCode The status code of HTTP response * @param headers The headers of HTTP response */ public ApiResponse(int statusCode, Map<String, List<String>> headers) { this(statusCode, headers, null); } /** * @param statusCode The status code of HTTP response * @param headers The headers of HTTP response * @param data The object deserialized from response bod */ public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) { this.statusCode = statusCode; this.headers = headers; this.data = data; } public int getStatusCode() { return statusCode; } public Map<String, List<String>> getHeaders() { return headers; } public T getData() { return data; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/Configuration.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch; @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); /** * Get the default API client, which would be used when creating API * instances without providing an API client. * * @return Default API client */ public static ApiClient getDefaultApiClient() { return defaultApiClient; } /** * Set the default API client, which would be used when creating API * instances without providing an API client. * * @param apiClient API client */ public static void setDefaultApiClient(ApiClient apiClient) { defaultApiClient = apiClient; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/GzipRequestInterceptor.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch; import com.squareup.okhttp.*; import okio.Buffer; import okio.BufferedSink; import okio.GzipSink; import okio.Okio; import java.io.IOException; /** * Encodes request bodies using gzip. * * Taken from https://github.com/square/okhttp/issues/350 */ class GzipRequestInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { return chain.proceed(originalRequest); } Request compressedRequest = originalRequest.newBuilder() .header("Content-Encoding", "gzip") .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))) .build(); return chain.proceed(compressedRequest); } private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { final Buffer buffer = new Buffer(); requestBody.writeTo(buffer); return new RequestBody() { @Override public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() { return buffer.size(); } @Override public void writeTo(BufferedSink sink) throws IOException { sink.write(buffer.snapshot()); } }; } private RequestBody gzip(final RequestBody body) { return new RequestBody() { @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return -1; // We don't know the compressed length in advance! } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); body.writeTo(gzipSink); gzipSink.close(); } }; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/JSON.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Type; import java.util.Date; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; public class JSON { private ApiClient apiClient; private Gson gson; /** * JSON constructor. * * @param apiClient An instance of ApiClient */ public JSON(ApiClient apiClient) { this.apiClient = apiClient; gson = new GsonBuilder() .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) .create(); } /** * Get Gson. * * @return Gson */ public Gson getGson() { return gson; } /** * Set Gson. * * @param gson Gson */ public void setGson(Gson gson) { this.gson = gson; } /** * Serialize the given Java object into JSON string. * * @param obj Object * @return String representation of the JSON */ public String serialize(Object obj) { return gson.toJson(obj); } /** * Deserialize the given JSON string to Java object. * * @param <T> Type * @param body The JSON string * @param returnType The type to deserialize into * @return The deserialized Java object */ @SuppressWarnings("unchecked") public <T> T deserialize(String body, Type returnType) { try { if (apiClient.isLenientOnJson()) { JsonReader jsonReader = new JsonReader(new StringReader(body)); // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) jsonReader.setLenient(true); return gson.fromJson(jsonReader, returnType); } else { return gson.fromJson(body, returnType); } } catch (JsonParseException e) { // Fallback processing when failed to parse JSON form response body: // return the response body string directly for the String return type; // parse response body into date or datetime for the Date return type. if (returnType.equals(String.class)) return (T) body; else if (returnType.equals(Date.class)) return (T) apiClient.parseDateOrDatetime(body); else throw(e); } } } class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> { private final ApiClient apiClient; /** * Constructor for DateAdapter * * @param apiClient Api client */ public DateAdapter(ApiClient apiClient) { super(); this.apiClient = apiClient; } /** * Serialize * * @param src Date * @param typeOfSrc Type * @param context Json Serialization Context * @return Json Element */ @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { if (src == null) { return JsonNull.INSTANCE; } else { return new JsonPrimitive(apiClient.formatDatetime(src)); } } /** * Deserialize * * @param json Json element * @param date Type * @param context Json Serialization Context * @return Date * @throws JsonParseException if fail to parse */ @Override public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { String str = json.getAsJsonPrimitive().getAsString(); try { return apiClient.parseDateOrDatetime(str); } catch (RuntimeException e) { throw new JsonParseException(e); } } } /** * Gson TypeAdapter for Joda DateTime type */ class DateTimeTypeAdapter extends TypeAdapter<DateTime> { private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { out.value(printFormatter.print(date)); } } @Override public DateTime read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); return parseFormatter.parseDateTime(date); } } } /** * Gson TypeAdapter for Joda LocalDate type */ class LocalDateTypeAdapter extends TypeAdapter<LocalDate> { private final DateTimeFormatter formatter = ISODateTimeFormat.date(); @Override public void write(JsonWriter out, LocalDate date) throws IOException { if (date == null) { out.nullValue(); } else { out.value(formatter.print(date)); } } @Override public LocalDate read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; default: String date = in.nextString(); return formatter.parseLocalDate(date); } } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/Pair.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch; @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class Pair { private String name = ""; private String value = ""; public Pair (String name, String value) { setName(name); setValue(value); } private void setName(String name) { if (!isValidString(name)) return; this.name = name; } private void setValue(String value) { if (!isValidString(value)) return; this.value = value; } public String getName() { return this.name; } public String getValue() { return this.value; } private boolean isValidString(String arg) { if (arg == null) return false; if (arg.trim().isEmpty()) return false; return true; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/ProgressRequestBody.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.RequestBody; import java.io.IOException; import okio.Buffer; import okio.BufferedSink; import okio.ForwardingSink; import okio.Okio; import okio.Sink; public class ProgressRequestBody extends RequestBody { public interface ProgressRequestListener { void onRequestProgress(long bytesWritten, long contentLength, boolean done); } private final RequestBody requestBody; private final ProgressRequestListener progressListener; public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) { this.requestBody = requestBody; this.progressListener = progressListener; } @Override public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() throws IOException { return requestBody.contentLength(); } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink bufferedSink = Okio.buffer(sink(sink)); requestBody.writeTo(bufferedSink); bufferedSink.flush(); } private Sink sink(Sink sink) { return new ForwardingSink(sink) { long bytesWritten = 0L; long contentLength = 0L; @Override public void write(Buffer source, long byteCount) throws IOException { super.write(source, byteCount); if (contentLength == 0) { contentLength = contentLength(); } bytesWritten += byteCount; progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength); } }; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/ProgressResponseBody.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.ResponseBody; import java.io.IOException; import okio.Buffer; import okio.BufferedSource; import okio.ForwardingSource; import okio.Okio; import okio.Source; public class ProgressResponseBody extends ResponseBody { public interface ProgressListener { void update(long bytesRead, long contentLength, boolean done); } private final ResponseBody responseBody; private final ProgressListener progressListener; private BufferedSource bufferedSource; public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) { this.responseBody = responseBody; this.progressListener = progressListener; } @Override public MediaType contentType() { return responseBody.contentType(); } @Override public long contentLength() throws IOException { return responseBody.contentLength(); } @Override public BufferedSource source() throws IOException { if (bufferedSource == null) { bufferedSource = Okio.buffer(source(responseBody.source())); } return bufferedSource; } private Source source(Source source) { return new ForwardingSource(source) { long totalBytesRead = 0L; @Override public long read(Buffer sink, long byteCount) throws IOException { long bytesRead = super.read(sink, byteCount); // read() returns the number of bytes read, or -1 if this source is exhausted. totalBytesRead += bytesRead != -1 ? bytesRead : 0; progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1); return bytesRead; } }; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/StringUtil.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch; @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). * * @param array The array * @param value The value to search * @return true if the array contains the value */ public static boolean containsIgnoreCase(String[] array, String value) { for (String str : array) { if (value == null && str == null) return true; if (value != null && value.equalsIgnoreCase(str)) return true; } return false; } /** * Join an array of strings with the given separator. * <p> * Note: This might be replaced by utility method from commons-lang or guava someday * if one of those libraries is added as dependency. * </p> * * @param array The array of strings * @param separator The separator * @return the resulting string */ public static String join(String[] array, String separator) { int len = array.length; if (len == 0) return ""; StringBuilder out = new StringBuilder(); out.append(array[0]); for (int i = 1; i < len; i++) { out.append(separator).append(array[i]); } return out.toString(); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/AddPromotionApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.AddPromotion; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class AddPromotionApi { private ApiClient apiClient; public AddPromotionApi() { this(Configuration.getDefaultApiClient()); } public AddPromotionApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for addPromotion * @param JSON Pass added promotion info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain promotion info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call addPromotionCall(AddPromotion JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/add_promotion"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call addPromotionValidateBeforeCall(AddPromotion JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling addPromotion(Async)"); } com.squareup.okhttp.Call call = addPromotionCall(JSON, progressListener, progressRequestListener); return call; } /** * Use add_promotion to record when a user adds one or more promotions to their account. * * @param JSON Pass added promotion info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain promotion info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse addPromotion(AddPromotion JSON) throws ApiException { ApiResponse<EventResponse> resp = addPromotionWithHttpInfo(JSON); return resp.getData(); } /** * Use add_promotion to record when a user adds one or more promotions to their account. * * @param JSON Pass added promotion info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain promotion info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> addPromotionWithHttpInfo(AddPromotion JSON) throws ApiException { com.squareup.okhttp.Call call = addPromotionValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use add_promotion to record when a user adds one or more promotions to their account. (asynchronously) * * @param JSON Pass added promotion info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain promotion info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call addPromotionAsync(AddPromotion JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = addPromotionValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/AddToCartApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.AddToCart; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class AddToCartApi { private ApiClient apiClient; public AddToCartApi() { this(Configuration.getDefaultApiClient()); } public AddToCartApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for addToCart * @param JSON Pass added item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call addToCartCall(AddToCart JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/add_to_cart"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call addToCartValidateBeforeCall(AddToCart JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling addToCart(Async)"); } com.squareup.okhttp.Call call = addToCartCall(JSON, progressListener, progressRequestListener); return call; } /** * Use add_to_cart when a user adds an item to their shopping cart or list. * * @param JSON Pass added item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse addToCart(AddToCart JSON) throws ApiException { ApiResponse<EventResponse> resp = addToCartWithHttpInfo(JSON); return resp.getData(); } /** * Use add_to_cart when a user adds an item to their shopping cart or list. * * @param JSON Pass added item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> addToCartWithHttpInfo(AddToCart JSON) throws ApiException { com.squareup.okhttp.Call call = addToCartValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use add_to_cart when a user adds an item to their shopping cart or list. (asynchronously) * * @param JSON Pass added item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call addToCartAsync(AddToCart JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = addToCartValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/ChargebackApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.Chargeback; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ChargebackApi { private ApiClient apiClient; public ChargebackApi() { this(Configuration.getDefaultApiClient()); } public ChargebackApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for chargeback * @param JSON Pass chargeback to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain chargeback info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call chargebackCall(Chargeback JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/chargeback"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call chargebackValidateBeforeCall(Chargeback JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling chargeback(Async)"); } com.squareup.okhttp.Call call = chargebackCall(JSON, progressListener, progressRequestListener); return call; } /** * Use chargeback to capture a chargeback reported on a transaction. This event can be called multiple times to record changes to the chargeback state. * Note - When you send a chargeback event you also need to send a label event if you want to prevent the user from making another purchase. * @param JSON Pass chargeback to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain chargeback info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse chargeback(Chargeback JSON) throws ApiException { ApiResponse<EventResponse> resp = chargebackWithHttpInfo(JSON); return resp.getData(); } /** * Use chargeback to capture a chargeback reported on a transaction. This event can be called multiple times to record changes to the chargeback state. * Note - When you send a chargeback event you also need to send a label event if you want to prevent the user from making another purchase. * @param JSON Pass chargeback to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain chargeback info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> chargebackWithHttpInfo(Chargeback JSON) throws ApiException { com.squareup.okhttp.Call call = chargebackValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use chargeback to capture a chargeback reported on a transaction. This event can be called multiple times to record changes to the chargeback state. (asynchronously) * Note - When you send a chargeback event you also need to send a label event if you want to prevent the user from making another purchase. * @param JSON Pass chargeback to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain chargeback info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call chargebackAsync(Chargeback JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = chargebackValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/CreateAccountApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.CreateAccount; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CreateAccountApi { private ApiClient apiClient; public CreateAccountApi() { this(Configuration.getDefaultApiClient()); } public CreateAccountApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for createAccount * @param JSON Pass user details after registration. Only &#x60;_userID&#x60; is required field. But this should contain user info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call createAccountCall(CreateAccount JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/create_account"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createAccountValidateBeforeCall(CreateAccount JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling createAccount(Async)"); } com.squareup.okhttp.Call call = createAccountCall(JSON, progressListener, progressRequestListener); return call; } /** * Use create_account to pass user details at user registration. * * @param JSON Pass user details after registration. Only &#x60;_userID&#x60; is required field. But this should contain user info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse createAccount(CreateAccount JSON) throws ApiException { ApiResponse<EventResponse> resp = createAccountWithHttpInfo(JSON); return resp.getData(); } /** * Use create_account to pass user details at user registration. * * @param JSON Pass user details after registration. Only &#x60;_userID&#x60; is required field. But this should contain user info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> createAccountWithHttpInfo(CreateAccount JSON) throws ApiException { com.squareup.okhttp.Call call = createAccountValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use create_account to pass user details at user registration. (asynchronously) * * @param JSON Pass user details after registration. Only &#x60;_userID&#x60; is required field. But this should contain user info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call createAccountAsync(CreateAccount JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = createAccountValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/CreateOrderApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.CreateOrder; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CreateOrderApi { private ApiClient apiClient; public CreateOrderApi() { this(Configuration.getDefaultApiClient()); } public CreateOrderApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for createOrder * @param body An order to submit for review. Only &#x60;_userID&#x60; is required field. But this should contain order info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call createOrderCall(CreateOrder body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = body; // create path and map variables String localVarPath = "/v1/createOrder"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call createOrderValidateBeforeCall(CreateOrder body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'body' is set if (body == null) { throw new ApiException("Missing the required parameter 'body' when calling createOrder(Async)"); } com.squareup.okhttp.Call call = createOrderCall(body, progressListener, progressRequestListener); return call; } /** * Submit a new or existing order to Thirdwatch for review. This API should contain order item info, the payment info, and user identity info. * * @param body An order to submit for review. Only &#x60;_userID&#x60; is required field. But this should contain order info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse createOrder(CreateOrder body) throws ApiException { ApiResponse<EventResponse> resp = createOrderWithHttpInfo(body); return resp.getData(); } /** * Submit a new or existing order to Thirdwatch for review. This API should contain order item info, the payment info, and user identity info. * * @param body An order to submit for review. Only &#x60;_userID&#x60; is required field. But this should contain order info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> createOrderWithHttpInfo(CreateOrder body) throws ApiException { com.squareup.okhttp.Call call = createOrderValidateBeforeCall(body, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Submit a new or existing order to Thirdwatch for review. This API should contain order item info, the payment info, and user identity info. (asynchronously) * * @param body An order to submit for review. Only &#x60;_userID&#x60; is required field. But this should contain order info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call createOrderAsync(CreateOrder body, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = createOrderValidateBeforeCall(body, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/CustomEventApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.Custom; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CustomEventApi { private ApiClient apiClient; public CustomEventApi() { this(Configuration.getDefaultApiClient()); } public CustomEventApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for customEvent * @param JSON Pass order status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain custom info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call customEventCall(Custom JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/custom_event"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call customEventValidateBeforeCall(Custom JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling customEvent(Async)"); } com.squareup.okhttp.Call call = customEventCall(JSON, progressListener, progressRequestListener); return call; } /** * Use order_status to track the order processing workflow of a previously submitted order. * Custom events and fields capture user behavior and differences not covered by our reserved events and fields. For example, a location tracking business can create a custom event called trackLocation with custom fields that are relevant. * @param JSON Pass order status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain custom info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse customEvent(Custom JSON) throws ApiException { ApiResponse<EventResponse> resp = customEventWithHttpInfo(JSON); return resp.getData(); } /** * Use order_status to track the order processing workflow of a previously submitted order. * Custom events and fields capture user behavior and differences not covered by our reserved events and fields. For example, a location tracking business can create a custom event called trackLocation with custom fields that are relevant. * @param JSON Pass order status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain custom info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> customEventWithHttpInfo(Custom JSON) throws ApiException { com.squareup.okhttp.Call call = customEventValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use order_status to track the order processing workflow of a previously submitted order. (asynchronously) * Custom events and fields capture user behavior and differences not covered by our reserved events and fields. For example, a location tracking business can create a custom event called trackLocation with custom fields that are relevant. * @param JSON Pass order status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain custom info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call customEventAsync(Custom JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = customEventValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/ItemStatusApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.ItemStatus; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ItemStatusApi { private ApiClient apiClient; public ItemStatusApi() { this(Configuration.getDefaultApiClient()); } public ItemStatusApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for itemStatus * @param JSON Pass change item status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item status. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call itemStatusCall(ItemStatus JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/item_status"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call itemStatusValidateBeforeCall(ItemStatus JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling itemStatus(Async)"); } com.squareup.okhttp.Call call = itemStatusCall(JSON, progressListener, progressRequestListener); return call; } /** * Use item_status to update the status of item that you’ve already pass to Thirdwatch. * If the status is the only thing that’s changing about the item, use this as a convenient way to send status of the item after order processing. * @param JSON Pass change item status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item status. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse itemStatus(ItemStatus JSON) throws ApiException { ApiResponse<EventResponse> resp = itemStatusWithHttpInfo(JSON); return resp.getData(); } /** * Use item_status to update the status of item that you’ve already pass to Thirdwatch. * If the status is the only thing that’s changing about the item, use this as a convenient way to send status of the item after order processing. * @param JSON Pass change item status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item status. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> itemStatusWithHttpInfo(ItemStatus JSON) throws ApiException { com.squareup.okhttp.Call call = itemStatusValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use item_status to update the status of item that you’ve already pass to Thirdwatch. (asynchronously) * If the status is the only thing that’s changing about the item, use this as a convenient way to send status of the item after order processing. * @param JSON Pass change item status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item status. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call itemStatusAsync(ItemStatus JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = itemStatusValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/LinkSessionToUserApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.LinkSessionToUser; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class LinkSessionToUserApi { private ApiClient apiClient; public LinkSessionToUserApi() { this(Configuration.getDefaultApiClient()); } public LinkSessionToUserApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for linkSessionToUser * @param JSON Pass session and user to thirdwatch for link. Only &#x60;_userID&#x60; is required field. But this should contain session and user info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call linkSessionToUserCall(LinkSessionToUser JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/link_session_to_user"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call linkSessionToUserValidateBeforeCall(LinkSessionToUser JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling linkSessionToUser(Async)"); } com.squareup.okhttp.Call call = linkSessionToUserCall(JSON, progressListener, progressRequestListener); return call; } /** * Use link_session_to_user to associate specific session to a user. Generally used only in anonymous checkout workflows. * * @param JSON Pass session and user to thirdwatch for link. Only &#x60;_userID&#x60; is required field. But this should contain session and user info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse linkSessionToUser(LinkSessionToUser JSON) throws ApiException { ApiResponse<EventResponse> resp = linkSessionToUserWithHttpInfo(JSON); return resp.getData(); } /** * Use link_session_to_user to associate specific session to a user. Generally used only in anonymous checkout workflows. * * @param JSON Pass session and user to thirdwatch for link. Only &#x60;_userID&#x60; is required field. But this should contain session and user info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> linkSessionToUserWithHttpInfo(LinkSessionToUser JSON) throws ApiException { com.squareup.okhttp.Call call = linkSessionToUserValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use link_session_to_user to associate specific session to a user. Generally used only in anonymous checkout workflows. (asynchronously) * * @param JSON Pass session and user to thirdwatch for link. Only &#x60;_userID&#x60; is required field. But this should contain session and user info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call linkSessionToUserAsync(LinkSessionToUser JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = linkSessionToUserValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/LoginApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.Login; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class LoginApi { private ApiClient apiClient; public LoginApi() { this(Configuration.getDefaultApiClient()); } public LoginApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for login * @param JSON Pass login status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain login info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call loginCall(Login JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/login"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call loginValidateBeforeCall(Login JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling login(Async)"); } com.squareup.okhttp.Call call = loginCall(JSON, progressListener, progressRequestListener); return call; } /** * Use login to record when a user attempts to log in. * * @param JSON Pass login status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain login info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse login(Login JSON) throws ApiException { ApiResponse<EventResponse> resp = loginWithHttpInfo(JSON); return resp.getData(); } /** * Use login to record when a user attempts to log in. * * @param JSON Pass login status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain login info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> loginWithHttpInfo(Login JSON) throws ApiException { com.squareup.okhttp.Call call = loginValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use login to record when a user attempts to log in. (asynchronously) * * @param JSON Pass login status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain login info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call loginAsync(Login JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = loginValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/LogoutApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.Logout; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class LogoutApi { private ApiClient apiClient; public LogoutApi() { this(Configuration.getDefaultApiClient()); } public LogoutApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for logout * @param JSON Pass logout status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain logout info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call logoutCall(Logout JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/logout"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call logoutValidateBeforeCall(Logout JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling logout(Async)"); } com.squareup.okhttp.Call call = logoutCall(JSON, progressListener, progressRequestListener); return call; } /** * Use logout to record when a user logs out. * * @param JSON Pass logout status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain logout info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse logout(Logout JSON) throws ApiException { ApiResponse<EventResponse> resp = logoutWithHttpInfo(JSON); return resp.getData(); } /** * Use logout to record when a user logs out. * * @param JSON Pass logout status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain logout info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> logoutWithHttpInfo(Logout JSON) throws ApiException { com.squareup.okhttp.Call call = logoutValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use logout to record when a user logs out. (asynchronously) * * @param JSON Pass logout status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain logout info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call logoutAsync(Logout JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = logoutValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/OrderStatusApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.OrderStatus; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class OrderStatusApi { private ApiClient apiClient; public OrderStatusApi() { this(Configuration.getDefaultApiClient()); } public OrderStatusApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for orderStatus * @param JSON Pass order status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain order info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call orderStatusCall(OrderStatus JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/order_status"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call orderStatusValidateBeforeCall(OrderStatus JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling orderStatus(Async)"); } com.squareup.okhttp.Call call = orderStatusCall(JSON, progressListener, progressRequestListener); return call; } /** * Use order_status to track the order processing workflow of a previously submitted order. * For example, order_status can be used to indicate that an order has been held for review, canceled due to suspected fraud, or fulfilled. This event can be called multiple times to record changes an order&#39;s status. * @param JSON Pass order status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain order info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse orderStatus(OrderStatus JSON) throws ApiException { ApiResponse<EventResponse> resp = orderStatusWithHttpInfo(JSON); return resp.getData(); } /** * Use order_status to track the order processing workflow of a previously submitted order. * For example, order_status can be used to indicate that an order has been held for review, canceled due to suspected fraud, or fulfilled. This event can be called multiple times to record changes an order&#39;s status. * @param JSON Pass order status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain order info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> orderStatusWithHttpInfo(OrderStatus JSON) throws ApiException { com.squareup.okhttp.Call call = orderStatusValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use order_status to track the order processing workflow of a previously submitted order. (asynchronously) * For example, order_status can be used to indicate that an order has been held for review, canceled due to suspected fraud, or fulfilled. This event can be called multiple times to record changes an order&#39;s status. * @param JSON Pass order status to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain order info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call orderStatusAsync(OrderStatus JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = orderStatusValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/RemoveFromCartApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.RemoveFromCart; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RemoveFromCartApi { private ApiClient apiClient; public RemoveFromCartApi() { this(Configuration.getDefaultApiClient()); } public RemoveFromCartApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for removeFromCart * @param JSON Pass removed item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call removeFromCartCall(RemoveFromCart JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/remove_from_cart"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call removeFromCartValidateBeforeCall(RemoveFromCart JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling removeFromCart(Async)"); } com.squareup.okhttp.Call call = removeFromCartCall(JSON, progressListener, progressRequestListener); return call; } /** * Use remove_from_cart when a user removes an item from their shopping cart or list. * * @param JSON Pass removed item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse removeFromCart(RemoveFromCart JSON) throws ApiException { ApiResponse<EventResponse> resp = removeFromCartWithHttpInfo(JSON); return resp.getData(); } /** * Use remove_from_cart when a user removes an item from their shopping cart or list. * * @param JSON Pass removed item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> removeFromCartWithHttpInfo(RemoveFromCart JSON) throws ApiException { com.squareup.okhttp.Call call = removeFromCartValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use remove_from_cart when a user removes an item from their shopping cart or list. (asynchronously) * * @param JSON Pass removed item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call removeFromCartAsync(RemoveFromCart JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = removeFromCartValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/ReportItemApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.ReportItem; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ReportItemApi { private ApiClient apiClient; public ReportItemApi() { this(Configuration.getDefaultApiClient()); } public ReportItemApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for reportItem * @param JSON Pass report item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item id. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call reportItemCall(ReportItem JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/report_item"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call reportItemValidateBeforeCall(ReportItem JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling reportItem(Async)"); } com.squareup.okhttp.Call call = reportItemCall(JSON, progressListener, progressRequestListener); return call; } /** * Use report_item to let us know when another user reports that this item may violate your company’s policies. * If you have a feature like \&quot;Report Item\&quot; or \&quot;Flag this Item\&quot;, send that event to us using this. * @param JSON Pass report item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item id. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse reportItem(ReportItem JSON) throws ApiException { ApiResponse<EventResponse> resp = reportItemWithHttpInfo(JSON); return resp.getData(); } /** * Use report_item to let us know when another user reports that this item may violate your company’s policies. * If you have a feature like \&quot;Report Item\&quot; or \&quot;Flag this Item\&quot;, send that event to us using this. * @param JSON Pass report item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item id. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> reportItemWithHttpInfo(ReportItem JSON) throws ApiException { com.squareup.okhttp.Call call = reportItemValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use report_item to let us know when another user reports that this item may violate your company’s policies. (asynchronously) * If you have a feature like \&quot;Report Item\&quot; or \&quot;Flag this Item\&quot;, send that event to us using this. * @param JSON Pass report item info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain item id. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call reportItemAsync(ReportItem JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = reportItemValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/SendMessageApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.SendMessage; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SendMessageApi { private ApiClient apiClient; public SendMessageApi() { this(Configuration.getDefaultApiClient()); } public SendMessageApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for sendMessage * @param JSON Pass message to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain message info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call sendMessageCall(SendMessage JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/send_message"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call sendMessageValidateBeforeCall(SendMessage JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling sendMessage(Async)"); } com.squareup.okhttp.Call call = sendMessageCall(JSON, progressListener, progressRequestListener); return call; } /** * Use send_message to record when a user sends a message to other i.e. seller, support. * * @param JSON Pass message to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain message info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse sendMessage(SendMessage JSON) throws ApiException { ApiResponse<EventResponse> resp = sendMessageWithHttpInfo(JSON); return resp.getData(); } /** * Use send_message to record when a user sends a message to other i.e. seller, support. * * @param JSON Pass message to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain message info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> sendMessageWithHttpInfo(SendMessage JSON) throws ApiException { com.squareup.okhttp.Call call = sendMessageValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use send_message to record when a user sends a message to other i.e. seller, support. (asynchronously) * * @param JSON Pass message to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain message info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call sendMessageAsync(SendMessage JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = sendMessageValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/SubmitReviewApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.SubmitReview; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SubmitReviewApi { private ApiClient apiClient; public SubmitReviewApi() { this(Configuration.getDefaultApiClient()); } public SubmitReviewApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for submitReview * @param JSON Pass review to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain review info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call submitReviewCall(SubmitReview JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/submit_review"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call submitReviewValidateBeforeCall(SubmitReview JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling submitReview(Async)"); } com.squareup.okhttp.Call call = submitReviewCall(JSON, progressListener, progressRequestListener); return call; } /** * Use submit_review when a user-submitted review of a product or seller. * * @param JSON Pass review to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain review info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse submitReview(SubmitReview JSON) throws ApiException { ApiResponse<EventResponse> resp = submitReviewWithHttpInfo(JSON); return resp.getData(); } /** * Use submit_review when a user-submitted review of a product or seller. * * @param JSON Pass review to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain review info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> submitReviewWithHttpInfo(SubmitReview JSON) throws ApiException { com.squareup.okhttp.Call call = submitReviewValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use submit_review when a user-submitted review of a product or seller. (asynchronously) * * @param JSON Pass review to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain review info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call submitReviewAsync(SubmitReview JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = submitReviewValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/TagAPIApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.Tag; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TagAPIApi { private ApiClient apiClient; public TagAPIApi() { this(Configuration.getDefaultApiClient()); } public TagAPIApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for tagUser * @param JSON Pass user and it&#39;s info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain tag info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call tagUserCall(Tag JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/tag"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call tagUserValidateBeforeCall(Tag JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling tagUser(Async)"); } com.squareup.okhttp.Call call = tagUserCall(JSON, progressListener, progressRequestListener); return call; } /** * The Tag API enables you to tell Thirdwatch which of your users are bad and which are good. * By telling us who is bad and who is good, we can identify patterns that are unique to your business. Once you give this feedback, the platform instantly analyzes it and learns to identify good and bad behavior of other users more accurately. If you want to change an existing label for a user - for example, from bad to good - all you need to do is send a new label and we&#39;ll overwrite the existing value. * @param JSON Pass user and it&#39;s info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain tag info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse tagUser(Tag JSON) throws ApiException { ApiResponse<EventResponse> resp = tagUserWithHttpInfo(JSON); return resp.getData(); } /** * The Tag API enables you to tell Thirdwatch which of your users are bad and which are good. * By telling us who is bad and who is good, we can identify patterns that are unique to your business. Once you give this feedback, the platform instantly analyzes it and learns to identify good and bad behavior of other users more accurately. If you want to change an existing label for a user - for example, from bad to good - all you need to do is send a new label and we&#39;ll overwrite the existing value. * @param JSON Pass user and it&#39;s info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain tag info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> tagUserWithHttpInfo(Tag JSON) throws ApiException { com.squareup.okhttp.Call call = tagUserValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * The Tag API enables you to tell Thirdwatch which of your users are bad and which are good. (asynchronously) * By telling us who is bad and who is good, we can identify patterns that are unique to your business. Once you give this feedback, the platform instantly analyzes it and learns to identify good and bad behavior of other users more accurately. If you want to change an existing label for a user - for example, from bad to good - all you need to do is send a new label and we&#39;ll overwrite the existing value. * @param JSON Pass user and it&#39;s info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain tag info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call tagUserAsync(Tag JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = tagUserValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/TransactionApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.Transaction; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TransactionApi { private ApiClient apiClient; public TransactionApi() { this(Configuration.getDefaultApiClient()); } public TransactionApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for transaction * @param JSON Pass transaction results to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain transaction info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call transactionCall(Transaction JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/transaction"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call transactionValidateBeforeCall(Transaction JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling transaction(Async)"); } com.squareup.okhttp.Call call = transactionCall(JSON, progressListener, progressRequestListener); return call; } /** * Use transaction to record attempts results to Pay, Transfer money, Refund or other transactions. * * @param JSON Pass transaction results to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain transaction info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse transaction(Transaction JSON) throws ApiException { ApiResponse<EventResponse> resp = transactionWithHttpInfo(JSON); return resp.getData(); } /** * Use transaction to record attempts results to Pay, Transfer money, Refund or other transactions. * * @param JSON Pass transaction results to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain transaction info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> transactionWithHttpInfo(Transaction JSON) throws ApiException { com.squareup.okhttp.Call call = transactionValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use transaction to record attempts results to Pay, Transfer money, Refund or other transactions. (asynchronously) * * @param JSON Pass transaction results to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain transaction info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call transactionAsync(Transaction JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = transactionValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/UntagAPIApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.UnTag; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class UntagAPIApi { private ApiClient apiClient; public UntagAPIApi() { this(Configuration.getDefaultApiClient()); } public UntagAPIApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for unTagUser * @param JSON Pass user and it&#39;s info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain untag info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call unTagUserCall(UnTag JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/untag"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call unTagUserValidateBeforeCall(UnTag JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling unTagUser(Async)"); } com.squareup.okhttp.Call call = unTagUserCall(JSON, progressListener, progressRequestListener); return call; } /** * If you are unsure whether a user is bad or good, you can always remove tag and leave the user in a neutral state. * To untag a user for a particular abuse type, send the abuse_type key in json data. In the rare case that you want to remove all tags for all abuse types for a particular user, send without the abuse_type query parameter. * @param JSON Pass user and it&#39;s info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain untag info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse unTagUser(UnTag JSON) throws ApiException { ApiResponse<EventResponse> resp = unTagUserWithHttpInfo(JSON); return resp.getData(); } /** * If you are unsure whether a user is bad or good, you can always remove tag and leave the user in a neutral state. * To untag a user for a particular abuse type, send the abuse_type key in json data. In the rare case that you want to remove all tags for all abuse types for a particular user, send without the abuse_type query parameter. * @param JSON Pass user and it&#39;s info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain untag info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> unTagUserWithHttpInfo(UnTag JSON) throws ApiException { com.squareup.okhttp.Call call = unTagUserValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * If you are unsure whether a user is bad or good, you can always remove tag and leave the user in a neutral state. (asynchronously) * To untag a user for a particular abuse type, send the abuse_type key in json data. In the rare case that you want to remove all tags for all abuse types for a particular user, send without the abuse_type query parameter. * @param JSON Pass user and it&#39;s info to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain untag info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call unTagUserAsync(UnTag JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = unTagUserValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/UpdateAccountApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.UpdateAccount; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class UpdateAccountApi { private ApiClient apiClient; public UpdateAccountApi() { this(Configuration.getDefaultApiClient()); } public UpdateAccountApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for updateAccount * @param JSON Pass user details after update or change in user info. Only &#x60;_userID&#x60; is required field. But this should contain user info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call updateAccountCall(UpdateAccount JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/update_account"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call updateAccountValidateBeforeCall(UpdateAccount JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling updateAccount(Async)"); } com.squareup.okhttp.Call call = updateAccountCall(JSON, progressListener, progressRequestListener); return call; } /** * Use update_account to record changes to the user&#39;s account information. * For user accounts created before integration with Thirdwatch, there&#39;s no need to call &#x60;create_account&#x60; before &#x60;update_account&#x60;. Simply call &#x60;update_account&#x60; and we&#39;ll infer that account was created before integration. * @param JSON Pass user details after update or change in user info. Only &#x60;_userID&#x60; is required field. But this should contain user info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse updateAccount(UpdateAccount JSON) throws ApiException { ApiResponse<EventResponse> resp = updateAccountWithHttpInfo(JSON); return resp.getData(); } /** * Use update_account to record changes to the user&#39;s account information. * For user accounts created before integration with Thirdwatch, there&#39;s no need to call &#x60;create_account&#x60; before &#x60;update_account&#x60;. Simply call &#x60;update_account&#x60; and we&#39;ll infer that account was created before integration. * @param JSON Pass user details after update or change in user info. Only &#x60;_userID&#x60; is required field. But this should contain user info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> updateAccountWithHttpInfo(UpdateAccount JSON) throws ApiException { com.squareup.okhttp.Call call = updateAccountValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Use update_account to record changes to the user&#39;s account information. (asynchronously) * For user accounts created before integration with Thirdwatch, there&#39;s no need to call &#x60;create_account&#x60; before &#x60;update_account&#x60;. Simply call &#x60;update_account&#x60; and we&#39;ll infer that account was created before integration. * @param JSON Pass user details after update or change in user info. Only &#x60;_userID&#x60; is required field. But this should contain user info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call updateAccountAsync(UpdateAccount JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = updateAccountValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/api/UpdateOrderApi.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.api; import ai.thirdwatch.ApiCallback; import ai.thirdwatch.ApiClient; import ai.thirdwatch.ApiException; import ai.thirdwatch.ApiResponse; import ai.thirdwatch.Configuration; import ai.thirdwatch.Pair; import ai.thirdwatch.ProgressRequestBody; import ai.thirdwatch.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import ai.thirdwatch.model.ErrorResponse; import ai.thirdwatch.model.EventResponse; import ai.thirdwatch.model.UpdateOrder; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class UpdateOrderApi { private ApiClient apiClient; public UpdateOrderApi() { this(Configuration.getDefaultApiClient()); } public UpdateOrderApi(ApiClient apiClient) { this.apiClient = apiClient; } public ApiClient getApiClient() { return apiClient; } public void setApiClient(ApiClient apiClient) { this.apiClient = apiClient; } /** * Build call for updateOrder * @param JSON Update details of an existing order. Only &#x60;_userID&#x60; is required field. But this should contain existing order info. (required) * @param progressListener Progress listener * @param progressRequestListener Progress request listener * @return Call to execute * @throws ApiException If fail to serialize the request body object */ public com.squareup.okhttp.Call updateOrderCall(UpdateOrder JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = JSON; // create path and map variables String localVarPath = "/v1/update_order"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); if(progressListener != null) { apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { @Override public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); } String[] localVarAuthNames = new String[] { "api_key" }; return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); } @SuppressWarnings("rawtypes") private com.squareup.okhttp.Call updateOrderValidateBeforeCall(UpdateOrder JSON, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { // verify the required parameter 'JSON' is set if (JSON == null) { throw new ApiException("Missing the required parameter 'JSON' when calling updateOrder(Async)"); } com.squareup.okhttp.Call call = updateOrderCall(JSON, progressListener, progressRequestListener); return call; } /** * Update details of an existing order. * * This event contains the same fields as &#x60;&#x60;&#x60;create_order&#x60;&#x60;&#x60;. * The existing order will be completely replaced by the values sent in &#x60;update_order&#x60;. Be sure to specify all values for the order, not just those that changed. * If no matching &#x60;_orderId&#x60; found, a new order will be created. * @param JSON Update details of an existing order. Only &#x60;_userID&#x60; is required field. But this should contain existing order info. (required) * @return EventResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public EventResponse updateOrder(UpdateOrder JSON) throws ApiException { ApiResponse<EventResponse> resp = updateOrderWithHttpInfo(JSON); return resp.getData(); } /** * Update details of an existing order. * * This event contains the same fields as &#x60;&#x60;&#x60;create_order&#x60;&#x60;&#x60;. * The existing order will be completely replaced by the values sent in &#x60;update_order&#x60;. Be sure to specify all values for the order, not just those that changed. * If no matching &#x60;_orderId&#x60; found, a new order will be created. * @param JSON Update details of an existing order. Only &#x60;_userID&#x60; is required field. But this should contain existing order info. (required) * @return ApiResponse&lt;EventResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<EventResponse> updateOrderWithHttpInfo(UpdateOrder JSON) throws ApiException { com.squareup.okhttp.Call call = updateOrderValidateBeforeCall(JSON, null, null); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Update details of an existing order. (asynchronously) * * This event contains the same fields as &#x60;&#x60;&#x60;create_order&#x60;&#x60;&#x60;. * The existing order will be completely replaced by the values sent in &#x60;update_order&#x60;. Be sure to specify all values for the order, not just those that changed. * If no matching &#x60;_orderId&#x60; found, a new order will be created. * @param JSON Update details of an existing order. Only &#x60;_userID&#x60; is required field. But this should contain existing order info. (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call updateOrderAsync(UpdateOrder JSON, final ApiCallback<EventResponse> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = updateOrderValidateBeforeCall(JSON, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<EventResponse>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/auth/ApiKeyAuth.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.auth; import ai.thirdwatch.Pair; import java.util.Map; import java.util.List; @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; private String apiKey; private String apiKeyPrefix; public ApiKeyAuth(String location, String paramName) { this.location = location; this.paramName = paramName; } public String getLocation() { return location; } public String getParamName() { return paramName; } public String getApiKey() { return apiKey; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public String getApiKeyPrefix() { return apiKeyPrefix; } public void setApiKeyPrefix(String apiKeyPrefix) { this.apiKeyPrefix = apiKeyPrefix; } @Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { if (apiKey == null) { return; } String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; } else { value = apiKey; } if ("query".equals(location)) { queryParams.add(new Pair(paramName, value)); } else if ("header".equals(location)) { headerParams.put(paramName, value); } } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/auth/Authentication.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.auth; import ai.thirdwatch.Pair; import java.util.Map; import java.util.List; public interface Authentication { /** * Apply authentication settings to header and query params. * * @param queryParams List of query parameters * @param headerParams Map of header parameters */ void applyToParams(List<Pair> queryParams, Map<String, String> headerParams); }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/auth/HttpBasicAuth.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.auth; import ai.thirdwatch.Pair; import com.squareup.okhttp.Credentials; import java.util.Map; import java.util.List; import java.io.UnsupportedEncodingException; public class HttpBasicAuth implements Authentication { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { if (username == null && password == null) { return; } headerParams.put("Authorization", Credentials.basic( username == null ? "" : username, password == null ? "" : password)); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/auth/OAuth.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.auth; import ai.thirdwatch.Pair; import java.util.Map; import java.util.List; @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class OAuth implements Authentication { private String accessToken; public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } @Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { if (accessToken != null) { headerParams.put("Authorization", "Bearer " + accessToken); } } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/auth/OAuthFlow.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.auth; public enum OAuthFlow { accessCode, implicit, password, application }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/AddPromotion.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import ai.thirdwatch.model.Promotion; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * AddPromotion */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class AddPromotion { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_promotions") private List<Promotion> promotions = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public AddPromotion userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public AddPromotion sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public AddPromotion deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public AddPromotion originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public AddPromotion promotions(List<Promotion> promotions) { this.promotions = promotions; return this; } public AddPromotion addPromotionsItem(Promotion promotionsItem) { if (this.promotions == null) { this.promotions = new ArrayList<Promotion>(); } this.promotions.add(promotionsItem); return this; } /** * Contains all promotions that have been newly applied to the referenced user. * @return promotions **/ @ApiModelProperty(value = "Contains all promotions that have been newly applied to the referenced user.") public List<Promotion> getPromotions() { return promotions; } public void setPromotions(List<Promotion> promotions) { this.promotions = promotions; } public AddPromotion customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AddPromotion addPromotion = (AddPromotion) o; return Objects.equals(this.userId, addPromotion.userId) && Objects.equals(this.sessionId, addPromotion.sessionId) && Objects.equals(this.deviceIp, addPromotion.deviceIp) && Objects.equals(this.originTimestamp, addPromotion.originTimestamp) && Objects.equals(this.promotions, addPromotion.promotions) && Objects.equals(this.customInfo, addPromotion.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, deviceIp, originTimestamp, promotions, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AddPromotion {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" promotions: ").append(toIndentedString(promotions)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/AddToCart.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import ai.thirdwatch.model.Item; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * AddToCart */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class AddToCart { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_item") private Item item = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public AddToCart userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public AddToCart sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public AddToCart deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public AddToCart originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public AddToCart item(Item item) { this.item = item; return this; } /** * Get item * @return item **/ @ApiModelProperty(value = "") public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } public AddToCart customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AddToCart addToCart = (AddToCart) o; return Objects.equals(this.userId, addToCart.userId) && Objects.equals(this.sessionId, addToCart.sessionId) && Objects.equals(this.deviceIp, addToCart.deviceIp) && Objects.equals(this.originTimestamp, addToCart.originTimestamp) && Objects.equals(this.item, addToCart.item) && Objects.equals(this.customInfo, addToCart.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, deviceIp, originTimestamp, item, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AddToCart {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" item: ").append(toIndentedString(item)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/BillingAddress.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * The Address field type represents a physical address. The value must be a nested object with the appropriate address subfields. We extract many geolocation features from these values. An address is represented as a nested JSON object. */ @ApiModel(description = "The Address field type represents a physical address. The value must be a nested object with the appropriate address subfields. We extract many geolocation features from these values. An address is represented as a nested JSON object. ") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class BillingAddress { @SerializedName("_name") private String name = null; @SerializedName("_phone") private String phone = null; @SerializedName("_address1") private String address1 = null; @SerializedName("_address2") private String address2 = null; @SerializedName("_city") private String city = null; @SerializedName("_region") private String region = null; @SerializedName("_country") private String country = null; @SerializedName("_zipcode") private String zipcode = null; @SerializedName("_isOfficeAddress") private Boolean isOfficeAddress = null; @SerializedName("_isHomeAddress") private Boolean isHomeAddress = null; public BillingAddress name(String name) { this.name = name; return this; } /** * Provide the full name associated with the address here. Concatenate first name and last name together if you collect them separately in your system. * @return name **/ @ApiModelProperty(value = "Provide the full name associated with the address here. Concatenate first name and last name together if you collect them separately in your system.") public String getName() { return name; } public void setName(String name) { this.name = name; } public BillingAddress phone(String phone) { this.phone = phone; return this; } /** * The phone number associated with this address. Provide the phone number as a string starting with the country code. Use E.164 format or send in the standard national format of number&#39;s origin. * @return phone **/ @ApiModelProperty(value = "The phone number associated with this address. Provide the phone number as a string starting with the country code. Use E.164 format or send in the standard national format of number's origin.") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public BillingAddress address1(String address1) { this.address1 = address1; return this; } /** * Address first line, e.g., \&quot;C802 Nirvana Courtyard\&quot;. * @return address1 **/ @ApiModelProperty(value = "Address first line, e.g., \"C802 Nirvana Courtyard\".") public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } public BillingAddress address2(String address2) { this.address2 = address2; return this; } /** * Address second line, e.g., \&quot;Nirvana Country, Sector 50\&quot;. * @return address2 **/ @ApiModelProperty(value = "Address second line, e.g., \"Nirvana Country, Sector 50\".") public String getAddress2() { return address2; } public void setAddress2(String address2) { this.address2 = address2; } public BillingAddress city(String city) { this.city = city; return this; } /** * The city or town name, e.g., \&quot;Gurgaon\&quot; . * @return city **/ @ApiModelProperty(value = "The city or town name, e.g., \"Gurgaon\" .") public String getCity() { return city; } public void setCity(String city) { this.city = city; } public BillingAddress region(String region) { this.region = region; return this; } /** * The region portion of the address. In the India, this corresponds to the state. * @return region **/ @ApiModelProperty(value = "The region portion of the address. In the India, this corresponds to the state.") public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public BillingAddress country(String country) { this.country = country; return this; } /** * The [ISO-3166](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code for the billing address, e.g., \&quot;IN\&quot; in case of India. * @return country **/ @ApiModelProperty(value = "The [ISO-3166](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code for the billing address, e.g., \"IN\" in case of India.") public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public BillingAddress zipcode(String zipcode) { this.zipcode = zipcode; return this; } /** * The postal code associated with the address, e.g., \&quot;122002\&quot;. * @return zipcode **/ @ApiModelProperty(value = "The postal code associated with the address, e.g., \"122002\".") public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } public BillingAddress isOfficeAddress(Boolean isOfficeAddress) { this.isOfficeAddress = isOfficeAddress; return this; } /** * Is user chosen this address as office address. * @return isOfficeAddress **/ @ApiModelProperty(value = "Is user chosen this address as office address.") public Boolean getIsOfficeAddress() { return isOfficeAddress; } public void setIsOfficeAddress(Boolean isOfficeAddress) { this.isOfficeAddress = isOfficeAddress; } public BillingAddress isHomeAddress(Boolean isHomeAddress) { this.isHomeAddress = isHomeAddress; return this; } /** * Is user chosen this address as home address. * @return isHomeAddress **/ @ApiModelProperty(value = "Is user chosen this address as home address.") public Boolean getIsHomeAddress() { return isHomeAddress; } public void setIsHomeAddress(Boolean isHomeAddress) { this.isHomeAddress = isHomeAddress; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BillingAddress billingAddress = (BillingAddress) o; return Objects.equals(this.name, billingAddress.name) && Objects.equals(this.phone, billingAddress.phone) && Objects.equals(this.address1, billingAddress.address1) && Objects.equals(this.address2, billingAddress.address2) && Objects.equals(this.city, billingAddress.city) && Objects.equals(this.region, billingAddress.region) && Objects.equals(this.country, billingAddress.country) && Objects.equals(this.zipcode, billingAddress.zipcode) && Objects.equals(this.isOfficeAddress, billingAddress.isOfficeAddress) && Objects.equals(this.isHomeAddress, billingAddress.isHomeAddress); } @Override public int hashCode() { return Objects.hash(name, phone, address1, address2, city, region, country, zipcode, isOfficeAddress, isHomeAddress); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class BillingAddress {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" address1: ").append(toIndentedString(address1)).append("\n"); sb.append(" address2: ").append(toIndentedString(address2)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" region: ").append(toIndentedString(region)).append("\n"); sb.append(" country: ").append(toIndentedString(country)).append("\n"); sb.append(" zipcode: ").append(toIndentedString(zipcode)).append("\n"); sb.append(" isOfficeAddress: ").append(toIndentedString(isOfficeAddress)).append("\n"); sb.append(" isHomeAddress: ").append(toIndentedString(isHomeAddress)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/Chargeback.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Chargeback */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class Chargeback { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_orderId") private String orderId = null; @SerializedName("_transactionId") private String transactionId = null; @SerializedName("_chargebackState") private String chargebackState = null; @SerializedName("_chargebackReason") private String chargebackReason = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public Chargeback userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Chargeback sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public Chargeback orderId(String orderId) { this.orderId = orderId; return this; } /** * The ID for the order that this chargeback is filed against. This field is not required if this chargeback was filed against a transaction with no _orderId. * @return orderId **/ @ApiModelProperty(value = "The ID for the order that this chargeback is filed against. This field is not required if this chargeback was filed against a transaction with no _orderId.") public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public Chargeback transactionId(String transactionId) { this.transactionId = transactionId; return this; } /** * The ID for the transaction that this chargeback is filed against. * @return transactionId **/ @ApiModelProperty(value = "The ID for the transaction that this chargeback is filed against.") public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public Chargeback chargebackState(String chargebackState) { this.chargebackState = chargebackState; return this; } /** * The current state of the chargeback. e.g. _received, _accepted, _disputed, _won, _lost * @return chargebackState **/ @ApiModelProperty(value = "The current state of the chargeback. e.g. _received, _accepted, _disputed, _won, _lost") public String getChargebackState() { return chargebackState; } public void setChargebackState(String chargebackState) { this.chargebackState = chargebackState; } public Chargeback chargebackReason(String chargebackReason) { this.chargebackReason = chargebackReason; return this; } /** * This field can be used to capture the reason given. e.g. _fraud, _duplicate, _product_not_received, _product_unacceptable, _other\&quot; * @return chargebackReason **/ @ApiModelProperty(value = "This field can be used to capture the reason given. e.g. _fraud, _duplicate, _product_not_received, _product_unacceptable, _other\"") public String getChargebackReason() { return chargebackReason; } public void setChargebackReason(String chargebackReason) { this.chargebackReason = chargebackReason; } public Chargeback customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Chargeback chargeback = (Chargeback) o; return Objects.equals(this.userId, chargeback.userId) && Objects.equals(this.sessionId, chargeback.sessionId) && Objects.equals(this.orderId, chargeback.orderId) && Objects.equals(this.transactionId, chargeback.transactionId) && Objects.equals(this.chargebackState, chargeback.chargebackState) && Objects.equals(this.chargebackReason, chargeback.chargebackReason) && Objects.equals(this.customInfo, chargeback.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, orderId, transactionId, chargebackState, chargebackReason, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Chargeback {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" transactionId: ").append(toIndentedString(transactionId)).append("\n"); sb.append(" chargebackState: ").append(toIndentedString(chargebackState)).append("\n"); sb.append(" chargebackReason: ").append(toIndentedString(chargebackReason)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/CreateAccount.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.BillingAddress; import ai.thirdwatch.model.CustomInfo; import ai.thirdwatch.model.PaymentMethod; import ai.thirdwatch.model.Promotion; import ai.thirdwatch.model.ShippingAddress; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * CreateAccount */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class CreateAccount { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_userEmail") private String userEmail = null; @SerializedName("_firstName") private String firstName = null; @SerializedName("_lastName") private String lastName = null; @SerializedName("_phone") private String phone = null; @SerializedName("_age") private String age = null; @SerializedName("_gender") private String gender = null; @SerializedName("_referralCode") private String referralCode = null; @SerializedName("_referrerUserId") private String referrerUserId = null; @SerializedName("_billingAddress") private BillingAddress billingAddress = null; @SerializedName("_shippingAddress") private ShippingAddress shippingAddress = null; @SerializedName("_paymentMethods") private List<PaymentMethod> paymentMethods = null; @SerializedName("_promotions") private List<Promotion> promotions = null; @SerializedName("_socialSignOnType") private String socialSignOnType = null; @SerializedName("_emailConfirmedStatus") private String emailConfirmedStatus = null; @SerializedName("_phoneConfirmedStatus") private String phoneConfirmedStatus = null; @SerializedName("_isNewsletterSubscribed") private Boolean isNewsletterSubscribed = null; @SerializedName("_accountStatus") private String accountStatus = null; @SerializedName("_facebookId") private String facebookId = null; @SerializedName("_googleId") private String googleId = null; @SerializedName("_twitterId") private String twitterId = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public CreateAccount userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public CreateAccount sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public CreateAccount deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public CreateAccount originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public CreateAccount userEmail(String userEmail) { this.userEmail = userEmail; return this; } /** * Email of the user creating this order. Note - If the user&#39;s email is also their account ID in your system, set both the userId and userEmail fields to their email address. * @return userEmail **/ @ApiModelProperty(value = "Email of the user creating this order. Note - If the user's email is also their account ID in your system, set both the userId and userEmail fields to their email address.") public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public CreateAccount firstName(String firstName) { this.firstName = firstName; return this; } /** * Provide the first name associated with the user here. * @return firstName **/ @ApiModelProperty(value = "Provide the first name associated with the user here.") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public CreateAccount lastName(String lastName) { this.lastName = lastName; return this; } /** * Provide the last name associated with the user here. * @return lastName **/ @ApiModelProperty(value = "Provide the last name associated with the user here.") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public CreateAccount phone(String phone) { this.phone = phone; return this; } /** * The primary phone number of the user associated with this account. Provide the phone number as a string. * @return phone **/ @ApiModelProperty(value = "The primary phone number of the user associated with this account. Provide the phone number as a string.") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public CreateAccount age(String age) { this.age = age; return this; } /** * Age of the user e.g. \&quot;25\&quot; * @return age **/ @ApiModelProperty(value = "Age of the user e.g. \"25\"") public String getAge() { return age; } public void setAge(String age) { this.age = age; } public CreateAccount gender(String gender) { this.gender = gender; return this; } /** * Gender of the user e.g. \&quot;_male\&quot;, \&quot;_female\&quot; or \&quot;_trans\&quot; * @return gender **/ @ApiModelProperty(value = "Gender of the user e.g. \"_male\", \"_female\" or \"_trans\"") public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public CreateAccount referralCode(String referralCode) { this.referralCode = referralCode; return this; } /** * Code or promotion used by the user while creating account. * @return referralCode **/ @ApiModelProperty(value = "Code or promotion used by the user while creating account.") public String getReferralCode() { return referralCode; } public void setReferralCode(String referralCode) { this.referralCode = referralCode; } public CreateAccount referrerUserId(String referrerUserId) { this.referrerUserId = referrerUserId; return this; } /** * The ID of the user that referred the current user to your business. This field is required for detecting referral fraud. * @return referrerUserId **/ @ApiModelProperty(value = "The ID of the user that referred the current user to your business. This field is required for detecting referral fraud.") public String getReferrerUserId() { return referrerUserId; } public void setReferrerUserId(String referrerUserId) { this.referrerUserId = referrerUserId; } public CreateAccount billingAddress(BillingAddress billingAddress) { this.billingAddress = billingAddress; return this; } /** * Get billingAddress * @return billingAddress **/ @ApiModelProperty(value = "") public BillingAddress getBillingAddress() { return billingAddress; } public void setBillingAddress(BillingAddress billingAddress) { this.billingAddress = billingAddress; } public CreateAccount shippingAddress(ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress; return this; } /** * Get shippingAddress * @return shippingAddress **/ @ApiModelProperty(value = "") public ShippingAddress getShippingAddress() { return shippingAddress; } public void setShippingAddress(ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress; } public CreateAccount paymentMethods(List<PaymentMethod> paymentMethods) { this.paymentMethods = paymentMethods; return this; } public CreateAccount addPaymentMethodsItem(PaymentMethod paymentMethodsItem) { if (this.paymentMethods == null) { this.paymentMethods = new ArrayList<PaymentMethod>(); } this.paymentMethods.add(paymentMethodsItem); return this; } /** * The payment information associated with this account. Represented as an array of nested payment_method objects containing payment type, payment gateway, credit card bin, etc. * @return paymentMethods **/ @ApiModelProperty(value = "The payment information associated with this account. Represented as an array of nested payment_method objects containing payment type, payment gateway, credit card bin, etc.") public List<PaymentMethod> getPaymentMethods() { return paymentMethods; } public void setPaymentMethods(List<PaymentMethod> paymentMethods) { this.paymentMethods = paymentMethods; } public CreateAccount promotions(List<Promotion> promotions) { this.promotions = promotions; return this; } public CreateAccount addPromotionsItem(Promotion promotionsItem) { if (this.promotions == null) { this.promotions = new ArrayList<Promotion>(); } this.promotions.add(promotionsItem); return this; } /** * The list of promotions that apply to this account. You can add one or more promotions when creating or updating an order. Represented as a JSON array of promotion objects. You can also separately add promotions to the account via the addPromotion event. * @return promotions **/ @ApiModelProperty(value = "The list of promotions that apply to this account. You can add one or more promotions when creating or updating an order. Represented as a JSON array of promotion objects. You can also separately add promotions to the account via the addPromotion event.") public List<Promotion> getPromotions() { return promotions; } public void setPromotions(List<Promotion> promotions) { this.promotions = promotions; } public CreateAccount socialSignOnType(String socialSignOnType) { this.socialSignOnType = socialSignOnType; return this; } /** * If the user logged in with a social identify provider, give the name here. e.g. _google, _facebook, _twitter, _linkedin, _other * @return socialSignOnType **/ @ApiModelProperty(value = "If the user logged in with a social identify provider, give the name here. e.g. _google, _facebook, _twitter, _linkedin, _other") public String getSocialSignOnType() { return socialSignOnType; } public void setSocialSignOnType(String socialSignOnType) { this.socialSignOnType = socialSignOnType; } public CreateAccount emailConfirmedStatus(String emailConfirmedStatus) { this.emailConfirmedStatus = emailConfirmedStatus; return this; } /** * Status of email verification. e.g. _success, _failure, _pending * @return emailConfirmedStatus **/ @ApiModelProperty(value = "Status of email verification. e.g. _success, _failure, _pending") public String getEmailConfirmedStatus() { return emailConfirmedStatus; } public void setEmailConfirmedStatus(String emailConfirmedStatus) { this.emailConfirmedStatus = emailConfirmedStatus; } public CreateAccount phoneConfirmedStatus(String phoneConfirmedStatus) { this.phoneConfirmedStatus = phoneConfirmedStatus; return this; } /** * Status of phone verification. e.g. _success, _failure, _pending * @return phoneConfirmedStatus **/ @ApiModelProperty(value = "Status of phone verification. e.g. _success, _failure, _pending") public String getPhoneConfirmedStatus() { return phoneConfirmedStatus; } public void setPhoneConfirmedStatus(String phoneConfirmedStatus) { this.phoneConfirmedStatus = phoneConfirmedStatus; } public CreateAccount isNewsletterSubscribed(Boolean isNewsletterSubscribed) { this.isNewsletterSubscribed = isNewsletterSubscribed; return this; } /** * Is user subscribed for newsletter. e.g. true, false * @return isNewsletterSubscribed **/ @ApiModelProperty(value = "Is user subscribed for newsletter. e.g. true, false") public Boolean getIsNewsletterSubscribed() { return isNewsletterSubscribed; } public void setIsNewsletterSubscribed(Boolean isNewsletterSubscribed) { this.isNewsletterSubscribed = isNewsletterSubscribed; } public CreateAccount accountStatus(String accountStatus) { this.accountStatus = accountStatus; return this; } /** * Current status of account, e.g. _active, _inactive * @return accountStatus **/ @ApiModelProperty(value = "Current status of account, e.g. _active, _inactive") public String getAccountStatus() { return accountStatus; } public void setAccountStatus(String accountStatus) { this.accountStatus = accountStatus; } public CreateAccount facebookId(String facebookId) { this.facebookId = facebookId; return this; } /** * Facebook user id or token of the user. This can help to varify his social identity. * @return facebookId **/ @ApiModelProperty(value = "Facebook user id or token of the user. This can help to varify his social identity.") public String getFacebookId() { return facebookId; } public void setFacebookId(String facebookId) { this.facebookId = facebookId; } public CreateAccount googleId(String googleId) { this.googleId = googleId; return this; } /** * Google user id or token of the user. This can help to varify his social identity. * @return googleId **/ @ApiModelProperty(value = "Google user id or token of the user. This can help to varify his social identity.") public String getGoogleId() { return googleId; } public void setGoogleId(String googleId) { this.googleId = googleId; } public CreateAccount twitterId(String twitterId) { this.twitterId = twitterId; return this; } /** * Twitter handle or token of the user. This can help to varify his social identity. * @return twitterId **/ @ApiModelProperty(value = "Twitter handle or token of the user. This can help to varify his social identity.") public String getTwitterId() { return twitterId; } public void setTwitterId(String twitterId) { this.twitterId = twitterId; } public CreateAccount customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateAccount createAccount = (CreateAccount) o; return Objects.equals(this.userId, createAccount.userId) && Objects.equals(this.sessionId, createAccount.sessionId) && Objects.equals(this.deviceIp, createAccount.deviceIp) && Objects.equals(this.originTimestamp, createAccount.originTimestamp) && Objects.equals(this.userEmail, createAccount.userEmail) && Objects.equals(this.firstName, createAccount.firstName) && Objects.equals(this.lastName, createAccount.lastName) && Objects.equals(this.phone, createAccount.phone) && Objects.equals(this.age, createAccount.age) && Objects.equals(this.gender, createAccount.gender) && Objects.equals(this.referralCode, createAccount.referralCode) && Objects.equals(this.referrerUserId, createAccount.referrerUserId) && Objects.equals(this.billingAddress, createAccount.billingAddress) && Objects.equals(this.shippingAddress, createAccount.shippingAddress) && Objects.equals(this.paymentMethods, createAccount.paymentMethods) && Objects.equals(this.promotions, createAccount.promotions) && Objects.equals(this.socialSignOnType, createAccount.socialSignOnType) && Objects.equals(this.emailConfirmedStatus, createAccount.emailConfirmedStatus) && Objects.equals(this.phoneConfirmedStatus, createAccount.phoneConfirmedStatus) && Objects.equals(this.isNewsletterSubscribed, createAccount.isNewsletterSubscribed) && Objects.equals(this.accountStatus, createAccount.accountStatus) && Objects.equals(this.facebookId, createAccount.facebookId) && Objects.equals(this.googleId, createAccount.googleId) && Objects.equals(this.twitterId, createAccount.twitterId) && Objects.equals(this.customInfo, createAccount.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, deviceIp, originTimestamp, userEmail, firstName, lastName, phone, age, gender, referralCode, referrerUserId, billingAddress, shippingAddress, paymentMethods, promotions, socialSignOnType, emailConfirmedStatus, phoneConfirmedStatus, isNewsletterSubscribed, accountStatus, facebookId, googleId, twitterId, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CreateAccount {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" userEmail: ").append(toIndentedString(userEmail)).append("\n"); sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" age: ").append(toIndentedString(age)).append("\n"); sb.append(" gender: ").append(toIndentedString(gender)).append("\n"); sb.append(" referralCode: ").append(toIndentedString(referralCode)).append("\n"); sb.append(" referrerUserId: ").append(toIndentedString(referrerUserId)).append("\n"); sb.append(" billingAddress: ").append(toIndentedString(billingAddress)).append("\n"); sb.append(" shippingAddress: ").append(toIndentedString(shippingAddress)).append("\n"); sb.append(" paymentMethods: ").append(toIndentedString(paymentMethods)).append("\n"); sb.append(" promotions: ").append(toIndentedString(promotions)).append("\n"); sb.append(" socialSignOnType: ").append(toIndentedString(socialSignOnType)).append("\n"); sb.append(" emailConfirmedStatus: ").append(toIndentedString(emailConfirmedStatus)).append("\n"); sb.append(" phoneConfirmedStatus: ").append(toIndentedString(phoneConfirmedStatus)).append("\n"); sb.append(" isNewsletterSubscribed: ").append(toIndentedString(isNewsletterSubscribed)).append("\n"); sb.append(" accountStatus: ").append(toIndentedString(accountStatus)).append("\n"); sb.append(" facebookId: ").append(toIndentedString(facebookId)).append("\n"); sb.append(" googleId: ").append(toIndentedString(googleId)).append("\n"); sb.append(" twitterId: ").append(toIndentedString(twitterId)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/CreateOrder.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.BillingAddress; import ai.thirdwatch.model.CustomInfo; import ai.thirdwatch.model.Item; import ai.thirdwatch.model.PaymentMethod; import ai.thirdwatch.model.Promotion; import ai.thirdwatch.model.ShippingAddress; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * CreateOrder */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class CreateOrder { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_orderId") private String orderId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_userEmail") private String userEmail = null; @SerializedName("_amount") private String amount = null; @SerializedName("_currencyCode") private String currencyCode = null; @SerializedName("_hasExpeditedShipping") private Boolean hasExpeditedShipping = null; @SerializedName("_shippingMethod") private String shippingMethod = null; @SerializedName("_orderReferrer") private String orderReferrer = null; @SerializedName("_isPrePaid") private Boolean isPrePaid = null; @SerializedName("_isGift") private Boolean isGift = null; @SerializedName("_isReturn") private Boolean isReturn = null; @SerializedName("_isFirstTimeBuyer") private Boolean isFirstTimeBuyer = null; @SerializedName("_billingAddress") private BillingAddress billingAddress = null; @SerializedName("_shippingAddress") private ShippingAddress shippingAddress = null; @SerializedName("_paymentMethods") private List<PaymentMethod> paymentMethods = null; @SerializedName("_promotions") private List<Promotion> promotions = null; @SerializedName("_items") private List<Item> items = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public CreateOrder userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public CreateOrder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public CreateOrder orderId(String orderId) { this.orderId = orderId; return this; } /** * The ID for tracking this order in your system. * @return orderId **/ @ApiModelProperty(required = true, value = "The ID for tracking this order in your system.") public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public CreateOrder deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public CreateOrder originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public CreateOrder userEmail(String userEmail) { this.userEmail = userEmail; return this; } /** * Email of the user creating this order. Note - If the user&#39;s email is also their account ID in your system, set both the userId and userEmail fields to their email address. * @return userEmail **/ @ApiModelProperty(value = "Email of the user creating this order. Note - If the user's email is also their account ID in your system, set both the userId and userEmail fields to their email address.") public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public CreateOrder amount(String amount) { this.amount = amount; return this; } /** * The item unit price in numbers, in the base unit of the currency_code.e.g. \&quot;2500\&quot; * @return amount **/ @ApiModelProperty(value = "The item unit price in numbers, in the base unit of the currency_code.e.g. \"2500\"") public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public CreateOrder currencyCode(String currencyCode) { this.currencyCode = currencyCode; return this; } /** * The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems. * @return currencyCode **/ @ApiModelProperty(value = "The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems.") public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public CreateOrder hasExpeditedShipping(Boolean hasExpeditedShipping) { this.hasExpeditedShipping = hasExpeditedShipping; return this; } /** * Whether the user requested priority/expedited shipping on their order. * @return hasExpeditedShipping **/ @ApiModelProperty(value = "Whether the user requested priority/expedited shipping on their order.") public Boolean getHasExpeditedShipping() { return hasExpeditedShipping; } public void setHasExpeditedShipping(Boolean hasExpeditedShipping) { this.hasExpeditedShipping = hasExpeditedShipping; } public CreateOrder shippingMethod(String shippingMethod) { this.shippingMethod = shippingMethod; return this; } /** * Indicates the method of delivery to the user. e.g. _electronic, _physical * @return shippingMethod **/ @ApiModelProperty(value = "Indicates the method of delivery to the user. e.g. _electronic, _physical") public String getShippingMethod() { return shippingMethod; } public void setShippingMethod(String shippingMethod) { this.shippingMethod = shippingMethod; } public CreateOrder orderReferrer(String orderReferrer) { this.orderReferrer = orderReferrer; return this; } /** * Referer website or user name. * @return orderReferrer **/ @ApiModelProperty(value = "Referer website or user name.") public String getOrderReferrer() { return orderReferrer; } public void setOrderReferrer(String orderReferrer) { this.orderReferrer = orderReferrer; } public CreateOrder isPrePaid(Boolean isPrePaid) { this.isPrePaid = isPrePaid; return this; } /** * is order is prepaid. * @return isPrePaid **/ @ApiModelProperty(value = "is order is prepaid.") public Boolean getIsPrePaid() { return isPrePaid; } public void setIsPrePaid(Boolean isPrePaid) { this.isPrePaid = isPrePaid; } public CreateOrder isGift(Boolean isGift) { this.isGift = isGift; return this; } /** * Is user chosen gift pack. * @return isGift **/ @ApiModelProperty(value = "Is user chosen gift pack.") public Boolean getIsGift() { return isGift; } public void setIsGift(Boolean isGift) { this.isGift = isGift; } public CreateOrder isReturn(Boolean isReturn) { this.isReturn = isReturn; return this; } /** * Is this return order. * @return isReturn **/ @ApiModelProperty(value = "Is this return order.") public Boolean getIsReturn() { return isReturn; } public void setIsReturn(Boolean isReturn) { this.isReturn = isReturn; } public CreateOrder isFirstTimeBuyer(Boolean isFirstTimeBuyer) { this.isFirstTimeBuyer = isFirstTimeBuyer; return this; } /** * Is user first time buyer. * @return isFirstTimeBuyer **/ @ApiModelProperty(value = "Is user first time buyer.") public Boolean getIsFirstTimeBuyer() { return isFirstTimeBuyer; } public void setIsFirstTimeBuyer(Boolean isFirstTimeBuyer) { this.isFirstTimeBuyer = isFirstTimeBuyer; } public CreateOrder billingAddress(BillingAddress billingAddress) { this.billingAddress = billingAddress; return this; } /** * Get billingAddress * @return billingAddress **/ @ApiModelProperty(value = "") public BillingAddress getBillingAddress() { return billingAddress; } public void setBillingAddress(BillingAddress billingAddress) { this.billingAddress = billingAddress; } public CreateOrder shippingAddress(ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress; return this; } /** * Get shippingAddress * @return shippingAddress **/ @ApiModelProperty(value = "") public ShippingAddress getShippingAddress() { return shippingAddress; } public void setShippingAddress(ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress; } public CreateOrder paymentMethods(List<PaymentMethod> paymentMethods) { this.paymentMethods = paymentMethods; return this; } public CreateOrder addPaymentMethodsItem(PaymentMethod paymentMethodsItem) { if (this.paymentMethods == null) { this.paymentMethods = new ArrayList<PaymentMethod>(); } this.paymentMethods.add(paymentMethodsItem); return this; } /** * The payment information associated with this order. Represented as an array of nested payment_method objects containing payment type, payment gateway, credit card bin, etc. * @return paymentMethods **/ @ApiModelProperty(value = "The payment information associated with this order. Represented as an array of nested payment_method objects containing payment type, payment gateway, credit card bin, etc.") public List<PaymentMethod> getPaymentMethods() { return paymentMethods; } public void setPaymentMethods(List<PaymentMethod> paymentMethods) { this.paymentMethods = paymentMethods; } public CreateOrder promotions(List<Promotion> promotions) { this.promotions = promotions; return this; } public CreateOrder addPromotionsItem(Promotion promotionsItem) { if (this.promotions == null) { this.promotions = new ArrayList<Promotion>(); } this.promotions.add(promotionsItem); return this; } /** * The list of promotions that apply to this order. You can add one or more promotions when creating or updating an order. Represented as a JSON array of promotion objects. You can also separately add promotions to the account via the addPromotion event. * @return promotions **/ @ApiModelProperty(value = "The list of promotions that apply to this order. You can add one or more promotions when creating or updating an order. Represented as a JSON array of promotion objects. You can also separately add promotions to the account via the addPromotion event.") public List<Promotion> getPromotions() { return promotions; } public void setPromotions(List<Promotion> promotions) { this.promotions = promotions; } public CreateOrder items(List<Item> items) { this.items = items; return this; } public CreateOrder addItemsItem(Item itemsItem) { if (this.items == null) { this.items = new ArrayList<Item>(); } this.items.add(itemsItem); return this; } /** * The list of items ordered. Represented as a JSON array of item * @return items **/ @ApiModelProperty(value = "The list of items ordered. Represented as a JSON array of item") public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } public CreateOrder customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateOrder createOrder = (CreateOrder) o; return Objects.equals(this.userId, createOrder.userId) && Objects.equals(this.sessionId, createOrder.sessionId) && Objects.equals(this.orderId, createOrder.orderId) && Objects.equals(this.deviceIp, createOrder.deviceIp) && Objects.equals(this.originTimestamp, createOrder.originTimestamp) && Objects.equals(this.userEmail, createOrder.userEmail) && Objects.equals(this.amount, createOrder.amount) && Objects.equals(this.currencyCode, createOrder.currencyCode) && Objects.equals(this.hasExpeditedShipping, createOrder.hasExpeditedShipping) && Objects.equals(this.shippingMethod, createOrder.shippingMethod) && Objects.equals(this.orderReferrer, createOrder.orderReferrer) && Objects.equals(this.isPrePaid, createOrder.isPrePaid) && Objects.equals(this.isGift, createOrder.isGift) && Objects.equals(this.isReturn, createOrder.isReturn) && Objects.equals(this.isFirstTimeBuyer, createOrder.isFirstTimeBuyer) && Objects.equals(this.billingAddress, createOrder.billingAddress) && Objects.equals(this.shippingAddress, createOrder.shippingAddress) && Objects.equals(this.paymentMethods, createOrder.paymentMethods) && Objects.equals(this.promotions, createOrder.promotions) && Objects.equals(this.items, createOrder.items) && Objects.equals(this.customInfo, createOrder.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, orderId, deviceIp, originTimestamp, userEmail, amount, currencyCode, hasExpeditedShipping, shippingMethod, orderReferrer, isPrePaid, isGift, isReturn, isFirstTimeBuyer, billingAddress, shippingAddress, paymentMethods, promotions, items, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CreateOrder {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" userEmail: ").append(toIndentedString(userEmail)).append("\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" currencyCode: ").append(toIndentedString(currencyCode)).append("\n"); sb.append(" hasExpeditedShipping: ").append(toIndentedString(hasExpeditedShipping)).append("\n"); sb.append(" shippingMethod: ").append(toIndentedString(shippingMethod)).append("\n"); sb.append(" orderReferrer: ").append(toIndentedString(orderReferrer)).append("\n"); sb.append(" isPrePaid: ").append(toIndentedString(isPrePaid)).append("\n"); sb.append(" isGift: ").append(toIndentedString(isGift)).append("\n"); sb.append(" isReturn: ").append(toIndentedString(isReturn)).append("\n"); sb.append(" isFirstTimeBuyer: ").append(toIndentedString(isFirstTimeBuyer)).append("\n"); sb.append(" billingAddress: ").append(toIndentedString(billingAddress)).append("\n"); sb.append(" shippingAddress: ").append(toIndentedString(shippingAddress)).append("\n"); sb.append(" paymentMethods: ").append(toIndentedString(paymentMethods)).append("\n"); sb.append(" promotions: ").append(toIndentedString(promotions)).append("\n"); sb.append(" items: ").append(toIndentedString(items)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/Custom.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Custom */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class Custom { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public Custom userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Custom sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public Custom deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public Custom originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public Custom customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Custom custom = (Custom) o; return Objects.equals(this.userId, custom.userId) && Objects.equals(this.sessionId, custom.sessionId) && Objects.equals(this.deviceIp, custom.deviceIp) && Objects.equals(this.originTimestamp, custom.originTimestamp) && Objects.equals(this.customInfo, custom.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, deviceIp, originTimestamp, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Custom {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/CustomInfo.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import java.util.HashMap; import java.util.Map; /** * Custom fields capture user behavior and differences not covered by our reserved events and fields. For example, you can pass extra info like latitude, longitude, search parameter etc. */ @ApiModel(description = "Custom fields capture user behavior and differences not covered by our reserved events and fields. For example, you can pass extra info like latitude, longitude, search parameter etc.") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class CustomInfo extends HashMap<String, String> { @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return super.equals(o); } @Override public int hashCode() { return Objects.hash(super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CustomInfo {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/ErrorResponse.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * ErrorResponse */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class ErrorResponse { @SerializedName("message") private String message = null; public ErrorResponse message(String message) { this.message = message; return this; } /** * Get message * @return message **/ @ApiModelProperty(required = true, value = "") public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ErrorResponse errorResponse = (ErrorResponse) o; return Objects.equals(this.message, errorResponse.message); } @Override public int hashCode() { return Objects.hash(message); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ErrorResponse {\n"); sb.append(" message: ").append(toIndentedString(message)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/EventResponse.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * EventResponse */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class EventResponse { @SerializedName("message") private String message = null; public EventResponse message(String message) { this.message = message; return this; } /** * Get message * @return message **/ @ApiModelProperty(required = true, value = "") public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EventResponse eventResponse = (EventResponse) o; return Objects.equals(this.message, eventResponse.message); } @Override public int hashCode() { return Objects.hash(message); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class EventResponse {\n"); sb.append(" message: ").append(toIndentedString(message)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/Item.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.Seller; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * The Item field type represents a product or service for sale in your business. The value must be a nested object with the appropriate item subfields. Generally used in the add_to_cart and remove_from_cart events. */ @ApiModel(description = "The Item field type represents a product or service for sale in your business. The value must be a nested object with the appropriate item subfields. Generally used in the add_to_cart and remove_from_cart events. ") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class Item { @SerializedName("_itemId") private String itemId = null; @SerializedName("_productTitle") private String productTitle = null; @SerializedName("_price") private String price = null; @SerializedName("_currencyCode") private String currencyCode = null; @SerializedName("_upc") private String upc = null; @SerializedName("_sku") private String sku = null; @SerializedName("_isbn") private String isbn = null; @SerializedName("_brand") private String brand = null; @SerializedName("_manufacturer") private String manufacturer = null; @SerializedName("_category") private String category = null; @SerializedName("_tags") private String tags = null; @SerializedName("_color") private String color = null; @SerializedName("_quantity") private Long quantity = null; @SerializedName("_isOnSale") private Boolean isOnSale = null; @SerializedName("_maxQuantity") private Long maxQuantity = null; @SerializedName("_discountPrice") private String discountPrice = null; @SerializedName("_productWeight") private String productWeight = null; @SerializedName("_country") private String country = null; @SerializedName("_descriptionShort") private String descriptionShort = null; @SerializedName("_description") private String description = null; @SerializedName("_seller") private Seller seller = null; public Item itemId(String itemId) { this.itemId = itemId; return this; } /** * The item&#39;s unique identifier according to your systems. Use the same ID that you would use to look up items on your website&#39;s database. * @return itemId **/ @ApiModelProperty(value = "The item's unique identifier according to your systems. Use the same ID that you would use to look up items on your website's database.") public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public Item productTitle(String productTitle) { this.productTitle = productTitle; return this; } /** * The item&#39;s name, e.g., \&quot;WD 2 TB External Hard Drive\&quot;. * @return productTitle **/ @ApiModelProperty(value = "The item's name, e.g., \"WD 2 TB External Hard Drive\".") public String getProductTitle() { return productTitle; } public void setProductTitle(String productTitle) { this.productTitle = productTitle; } public Item price(String price) { this.price = price; return this; } /** * The item unit price in numbers, in the base unit of the currency_code.e.g. \&quot;2500\&quot; * @return price **/ @ApiModelProperty(value = "The item unit price in numbers, in the base unit of the currency_code.e.g. \"2500\"") public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Item currencyCode(String currencyCode) { this.currencyCode = currencyCode; return this; } /** * The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems. * @return currencyCode **/ @ApiModelProperty(value = "The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems.") public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public Item upc(String upc) { this.upc = upc; return this; } /** * If the item has a Universal Product Code (UPC), provide it here. * @return upc **/ @ApiModelProperty(value = "If the item has a Universal Product Code (UPC), provide it here.") public String getUpc() { return upc; } public void setUpc(String upc) { this.upc = upc; } public Item sku(String sku) { this.sku = sku; return this; } /** * If the item has a Stock-keeping Unit ID (SKU), provide it here. * @return sku **/ @ApiModelProperty(value = "If the item has a Stock-keeping Unit ID (SKU), provide it here.") public String getSku() { return sku; } public void setSku(String sku) { this.sku = sku; } public Item isbn(String isbn) { this.isbn = isbn; return this; } /** * If the item is a book with an International Standard Book Number (ISBN), provide it here. * @return isbn **/ @ApiModelProperty(value = "If the item is a book with an International Standard Book Number (ISBN), provide it here.") public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public Item brand(String brand) { this.brand = brand; return this; } /** * The brand name of the item. * @return brand **/ @ApiModelProperty(value = "The brand name of the item.") public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public Item manufacturer(String manufacturer) { this.manufacturer = manufacturer; return this; } /** * Name of the item&#39;s manufacturer. * @return manufacturer **/ @ApiModelProperty(value = "Name of the item's manufacturer.") public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public Item category(String category) { this.category = category; return this; } /** * The category this item is listed under in your business. e.g., \&quot;travel\&quot;, \&quot;man &gt; bags\&quot;. * @return category **/ @ApiModelProperty(value = "The category this item is listed under in your business. e.g., \"travel\", \"man > bags\".") public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Item tags(String tags) { this.tags = tags; return this; } /** * The tags used to describe this item in your business. e.g., \&quot;man\&quot;, \&quot;summer\&quot;. * @return tags **/ @ApiModelProperty(value = "The tags used to describe this item in your business. e.g., \"man\", \"summer\".") public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public Item color(String color) { this.color = color; return this; } /** * The color of the item. * @return color **/ @ApiModelProperty(value = "The color of the item.") public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Item quantity(Long quantity) { this.quantity = quantity; return this; } /** * The quantity of the item. * @return quantity **/ @ApiModelProperty(value = "The quantity of the item.") public Long getQuantity() { return quantity; } public void setQuantity(Long quantity) { this.quantity = quantity; } public Item isOnSale(Boolean isOnSale) { this.isOnSale = isOnSale; return this; } /** * Is item on sale or running offers on this item . * @return isOnSale **/ @ApiModelProperty(value = "Is item on sale or running offers on this item .") public Boolean getIsOnSale() { return isOnSale; } public void setIsOnSale(Boolean isOnSale) { this.isOnSale = isOnSale; } public Item maxQuantity(Long maxQuantity) { this.maxQuantity = maxQuantity; return this; } /** * The max quantity per user for this item. * @return maxQuantity **/ @ApiModelProperty(value = "The max quantity per user for this item.") public Long getMaxQuantity() { return maxQuantity; } public void setMaxQuantity(Long maxQuantity) { this.maxQuantity = maxQuantity; } public Item discountPrice(String discountPrice) { this.discountPrice = discountPrice; return this; } /** * Price of the product after discount. * @return discountPrice **/ @ApiModelProperty(value = "Price of the product after discount.") public String getDiscountPrice() { return discountPrice; } public void setDiscountPrice(String discountPrice) { this.discountPrice = discountPrice; } public Item productWeight(String productWeight) { this.productWeight = productWeight; return this; } /** * Weight of the product in Kilo Gram, e.g. \&quot;3\&quot; , \&quot;0.5\&quot; * @return productWeight **/ @ApiModelProperty(value = "Weight of the product in Kilo Gram, e.g. \"3\" , \"0.5\"") public String getProductWeight() { return productWeight; } public void setProductWeight(String productWeight) { this.productWeight = productWeight; } public Item country(String country) { this.country = country; return this; } /** * The [ISO-3166](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the item, e.g., \&quot;IN\&quot; in case of India. * @return country **/ @ApiModelProperty(value = "The [ISO-3166](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the item, e.g., \"IN\" in case of India.") public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public Item descriptionShort(String descriptionShort) { this.descriptionShort = descriptionShort; return this; } /** * Short description of the item. * @return descriptionShort **/ @ApiModelProperty(value = "Short description of the item.") public String getDescriptionShort() { return descriptionShort; } public void setDescriptionShort(String descriptionShort) { this.descriptionShort = descriptionShort; } public Item description(String description) { this.description = description; return this; } /** * Detail description of the item. * @return description **/ @ApiModelProperty(value = "Detail description of the item.") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Item seller(Seller seller) { this.seller = seller; return this; } /** * Get seller * @return seller **/ @ApiModelProperty(value = "") public Seller getSeller() { return seller; } public void setSeller(Seller seller) { this.seller = seller; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Item item = (Item) o; return Objects.equals(this.itemId, item.itemId) && Objects.equals(this.productTitle, item.productTitle) && Objects.equals(this.price, item.price) && Objects.equals(this.currencyCode, item.currencyCode) && Objects.equals(this.upc, item.upc) && Objects.equals(this.sku, item.sku) && Objects.equals(this.isbn, item.isbn) && Objects.equals(this.brand, item.brand) && Objects.equals(this.manufacturer, item.manufacturer) && Objects.equals(this.category, item.category) && Objects.equals(this.tags, item.tags) && Objects.equals(this.color, item.color) && Objects.equals(this.quantity, item.quantity) && Objects.equals(this.isOnSale, item.isOnSale) && Objects.equals(this.maxQuantity, item.maxQuantity) && Objects.equals(this.discountPrice, item.discountPrice) && Objects.equals(this.productWeight, item.productWeight) && Objects.equals(this.country, item.country) && Objects.equals(this.descriptionShort, item.descriptionShort) && Objects.equals(this.description, item.description) && Objects.equals(this.seller, item.seller); } @Override public int hashCode() { return Objects.hash(itemId, productTitle, price, currencyCode, upc, sku, isbn, brand, manufacturer, category, tags, color, quantity, isOnSale, maxQuantity, discountPrice, productWeight, country, descriptionShort, description, seller); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Item {\n"); sb.append(" itemId: ").append(toIndentedString(itemId)).append("\n"); sb.append(" productTitle: ").append(toIndentedString(productTitle)).append("\n"); sb.append(" price: ").append(toIndentedString(price)).append("\n"); sb.append(" currencyCode: ").append(toIndentedString(currencyCode)).append("\n"); sb.append(" upc: ").append(toIndentedString(upc)).append("\n"); sb.append(" sku: ").append(toIndentedString(sku)).append("\n"); sb.append(" isbn: ").append(toIndentedString(isbn)).append("\n"); sb.append(" brand: ").append(toIndentedString(brand)).append("\n"); sb.append(" manufacturer: ").append(toIndentedString(manufacturer)).append("\n"); sb.append(" category: ").append(toIndentedString(category)).append("\n"); sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); sb.append(" color: ").append(toIndentedString(color)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" isOnSale: ").append(toIndentedString(isOnSale)).append("\n"); sb.append(" maxQuantity: ").append(toIndentedString(maxQuantity)).append("\n"); sb.append(" discountPrice: ").append(toIndentedString(discountPrice)).append("\n"); sb.append(" productWeight: ").append(toIndentedString(productWeight)).append("\n"); sb.append(" country: ").append(toIndentedString(country)).append("\n"); sb.append(" descriptionShort: ").append(toIndentedString(descriptionShort)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" seller: ").append(toIndentedString(seller)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/ItemStatus.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * ItemStatus */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class ItemStatus { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_orderId") private String orderId = null; @SerializedName("_itemId") private String itemId = null; @SerializedName("_itemStatus") private String itemStatus = null; @SerializedName("_reason") private String reason = null; @SerializedName("_shippingCost") private String shippingCost = null; @SerializedName("_trackingNumber") private String trackingNumber = null; @SerializedName("_trackingMethod") private String trackingMethod = null; @SerializedName("_source") private String source = null; @SerializedName("_analyst") private String analyst = null; @SerializedName("_description") private String description = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public ItemStatus userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public ItemStatus sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public ItemStatus orderId(String orderId) { this.orderId = orderId; return this; } /** * The ID for the order that this chargeback is filed against. This field is not required if this chargeback was filed against a transaction with no _orderId. * @return orderId **/ @ApiModelProperty(value = "The ID for the order that this chargeback is filed against. This field is not required if this chargeback was filed against a transaction with no _orderId.") public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public ItemStatus itemId(String itemId) { this.itemId = itemId; return this; } /** * The item&#39;s unique identifier according to your systems. Use the same ID that you would use to look up items on your website&#39;s database. * @return itemId **/ @ApiModelProperty(value = "The item's unique identifier according to your systems. Use the same ID that you would use to look up items on your website's database.") public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public ItemStatus itemStatus(String itemStatus) { this.itemStatus = itemStatus; return this; } /** * Indicates the high-level state of the order. e.g. _approved, _canceled, _held, _fulfilled, _returned, _rto * @return itemStatus **/ @ApiModelProperty(value = "Indicates the high-level state of the order. e.g. _approved, _canceled, _held, _fulfilled, _returned, _rto") public String getItemStatus() { return itemStatus; } public void setItemStatus(String itemStatus) { this.itemStatus = itemStatus; } public ItemStatus reason(String reason) { this.reason = reason; return this; } /** * The reason for a cancellation. e.g. _paymentRisk, _abuse, _policy, _other * @return reason **/ @ApiModelProperty(value = "The reason for a cancellation. e.g. _paymentRisk, _abuse, _policy, _other") public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public ItemStatus shippingCost(String shippingCost) { this.shippingCost = shippingCost; return this; } /** * if _approved or _fulfilled than pass the shipping cost. e.g. \&quot;50\&quot; * @return shippingCost **/ @ApiModelProperty(value = "if _approved or _fulfilled than pass the shipping cost. e.g. \"50\"") public String getShippingCost() { return shippingCost; } public void setShippingCost(String shippingCost) { this.shippingCost = shippingCost; } public ItemStatus trackingNumber(String trackingNumber) { this.trackingNumber = trackingNumber; return this; } /** * if _approved or _fulfilled than pass the tracking number. e.g. \&quot;55327470\&quot; * @return trackingNumber **/ @ApiModelProperty(value = "if _approved or _fulfilled than pass the tracking number. e.g. \"55327470\"") public String getTrackingNumber() { return trackingNumber; } public void setTrackingNumber(String trackingNumber) { this.trackingNumber = trackingNumber; } public ItemStatus trackingMethod(String trackingMethod) { this.trackingMethod = trackingMethod; return this; } /** * if _approved or _fulfilled than pass the tracking url. e.g. \&quot;http://fedex.com/track?q&#x3D;abc123\&quot; * @return trackingMethod **/ @ApiModelProperty(value = "if _approved or _fulfilled than pass the tracking url. e.g. \"http://fedex.com/track?q=abc123\"") public String getTrackingMethod() { return trackingMethod; } public void setTrackingMethod(String trackingMethod) { this.trackingMethod = trackingMethod; } public ItemStatus source(String source) { this.source = source; return this; } /** * The source of a decision. e.g. _automated, _manualReview\&quot; * @return source **/ @ApiModelProperty(value = "The source of a decision. e.g. _automated, _manualReview\"") public String getSource() { return source; } public void setSource(String source) { this.source = source; } public ItemStatus analyst(String analyst) { this.analyst = analyst; return this; } /** * The analyst who made the decision, if manual. * @return analyst **/ @ApiModelProperty(value = "The analyst who made the decision, if manual.") public String getAnalyst() { return analyst; } public void setAnalyst(String analyst) { this.analyst = analyst; } public ItemStatus description(String description) { this.description = description; return this; } /** * Any additional information about this order status change. * @return description **/ @ApiModelProperty(value = "Any additional information about this order status change.") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ItemStatus customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ItemStatus itemStatus = (ItemStatus) o; return Objects.equals(this.userId, itemStatus.userId) && Objects.equals(this.sessionId, itemStatus.sessionId) && Objects.equals(this.orderId, itemStatus.orderId) && Objects.equals(this.itemId, itemStatus.itemId) && Objects.equals(this.itemStatus, itemStatus.itemStatus) && Objects.equals(this.reason, itemStatus.reason) && Objects.equals(this.shippingCost, itemStatus.shippingCost) && Objects.equals(this.trackingNumber, itemStatus.trackingNumber) && Objects.equals(this.trackingMethod, itemStatus.trackingMethod) && Objects.equals(this.source, itemStatus.source) && Objects.equals(this.analyst, itemStatus.analyst) && Objects.equals(this.description, itemStatus.description) && Objects.equals(this.customInfo, itemStatus.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, orderId, itemId, itemStatus, reason, shippingCost, trackingNumber, trackingMethod, source, analyst, description, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ItemStatus {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" itemId: ").append(toIndentedString(itemId)).append("\n"); sb.append(" itemStatus: ").append(toIndentedString(itemStatus)).append("\n"); sb.append(" reason: ").append(toIndentedString(reason)).append("\n"); sb.append(" shippingCost: ").append(toIndentedString(shippingCost)).append("\n"); sb.append(" trackingNumber: ").append(toIndentedString(trackingNumber)).append("\n"); sb.append(" trackingMethod: ").append(toIndentedString(trackingMethod)).append("\n"); sb.append(" source: ").append(toIndentedString(source)).append("\n"); sb.append(" analyst: ").append(toIndentedString(analyst)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/LinkSessionToUser.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * LinkSessionToUser */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class LinkSessionToUser { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public LinkSessionToUser userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public LinkSessionToUser sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to associate session id with user id. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to associate session id with user id.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public LinkSessionToUser customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LinkSessionToUser linkSessionToUser = (LinkSessionToUser) o; return Objects.equals(this.userId, linkSessionToUser.userId) && Objects.equals(this.sessionId, linkSessionToUser.sessionId) && Objects.equals(this.customInfo, linkSessionToUser.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LinkSessionToUser {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/Login.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Login */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class Login { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_loginStatus") private String loginStatus = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public Login userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Login sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public Login deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public Login originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public Login loginStatus(String loginStatus) { this.loginStatus = loginStatus; return this; } /** * Use _loginStatus to represent the success or failure of the login attempt. e.g. _success, _failure * @return loginStatus **/ @ApiModelProperty(value = "Use _loginStatus to represent the success or failure of the login attempt. e.g. _success, _failure") public String getLoginStatus() { return loginStatus; } public void setLoginStatus(String loginStatus) { this.loginStatus = loginStatus; } public Login customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Login login = (Login) o; return Objects.equals(this.userId, login.userId) && Objects.equals(this.sessionId, login.sessionId) && Objects.equals(this.deviceIp, login.deviceIp) && Objects.equals(this.originTimestamp, login.originTimestamp) && Objects.equals(this.loginStatus, login.loginStatus) && Objects.equals(this.customInfo, login.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, deviceIp, originTimestamp, loginStatus, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Login {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" loginStatus: ").append(toIndentedString(loginStatus)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/Logout.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Logout */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class Logout { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public Logout userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Logout sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public Logout deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public Logout originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public Logout customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Logout logout = (Logout) o; return Objects.equals(this.userId, logout.userId) && Objects.equals(this.sessionId, logout.sessionId) && Objects.equals(this.deviceIp, logout.deviceIp) && Objects.equals(this.originTimestamp, logout.originTimestamp) && Objects.equals(this.customInfo, logout.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, deviceIp, originTimestamp, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Logout {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/OrderStatus.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * OrderStatus */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class OrderStatus { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_orderId") private String orderId = null; @SerializedName("_orderStatus") private String orderStatus = null; @SerializedName("_reason") private String reason = null; @SerializedName("_shippingCost") private String shippingCost = null; @SerializedName("_trackingNumber") private String trackingNumber = null; @SerializedName("_trackingMethod") private String trackingMethod = null; @SerializedName("_source") private String source = null; @SerializedName("_analyst") private String analyst = null; @SerializedName("_description") private String description = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public OrderStatus userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public OrderStatus sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public OrderStatus orderId(String orderId) { this.orderId = orderId; return this; } /** * The ID for the order that this chargeback is filed against. This field is not required if this chargeback was filed against a transaction with no _orderId. * @return orderId **/ @ApiModelProperty(value = "The ID for the order that this chargeback is filed against. This field is not required if this chargeback was filed against a transaction with no _orderId.") public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public OrderStatus orderStatus(String orderStatus) { this.orderStatus = orderStatus; return this; } /** * Indicates the high-level state of the order. e.g. _approved, _canceled, _held, _fulfilled, _returned, _rto * @return orderStatus **/ @ApiModelProperty(value = "Indicates the high-level state of the order. e.g. _approved, _canceled, _held, _fulfilled, _returned, _rto") public String getOrderStatus() { return orderStatus; } public void setOrderStatus(String orderStatus) { this.orderStatus = orderStatus; } public OrderStatus reason(String reason) { this.reason = reason; return this; } /** * The reason for a cancellation. e.g. _paymentRisk, _abuse, _policy, _other * @return reason **/ @ApiModelProperty(value = "The reason for a cancellation. e.g. _paymentRisk, _abuse, _policy, _other") public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public OrderStatus shippingCost(String shippingCost) { this.shippingCost = shippingCost; return this; } /** * if _approved or _fulfilled than pass the shipping cost. e.g. \&quot;50\&quot; * @return shippingCost **/ @ApiModelProperty(value = "if _approved or _fulfilled than pass the shipping cost. e.g. \"50\"") public String getShippingCost() { return shippingCost; } public void setShippingCost(String shippingCost) { this.shippingCost = shippingCost; } public OrderStatus trackingNumber(String trackingNumber) { this.trackingNumber = trackingNumber; return this; } /** * if _approved or _fulfilled than pass the tracking number. e.g. \&quot;55327470\&quot; * @return trackingNumber **/ @ApiModelProperty(value = "if _approved or _fulfilled than pass the tracking number. e.g. \"55327470\"") public String getTrackingNumber() { return trackingNumber; } public void setTrackingNumber(String trackingNumber) { this.trackingNumber = trackingNumber; } public OrderStatus trackingMethod(String trackingMethod) { this.trackingMethod = trackingMethod; return this; } /** * if _approved or _fulfilled than pass the tracking url. e.g. \&quot;http://fedex.com/track?q&#x3D;abc123\&quot; * @return trackingMethod **/ @ApiModelProperty(value = "if _approved or _fulfilled than pass the tracking url. e.g. \"http://fedex.com/track?q=abc123\"") public String getTrackingMethod() { return trackingMethod; } public void setTrackingMethod(String trackingMethod) { this.trackingMethod = trackingMethod; } public OrderStatus source(String source) { this.source = source; return this; } /** * The source of a decision. e.g. _automated, _manualReview\&quot; * @return source **/ @ApiModelProperty(value = "The source of a decision. e.g. _automated, _manualReview\"") public String getSource() { return source; } public void setSource(String source) { this.source = source; } public OrderStatus analyst(String analyst) { this.analyst = analyst; return this; } /** * The analyst who made the decision, if manual. * @return analyst **/ @ApiModelProperty(value = "The analyst who made the decision, if manual.") public String getAnalyst() { return analyst; } public void setAnalyst(String analyst) { this.analyst = analyst; } public OrderStatus description(String description) { this.description = description; return this; } /** * Any additional information about this order status change. * @return description **/ @ApiModelProperty(value = "Any additional information about this order status change.") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public OrderStatus customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderStatus orderStatus = (OrderStatus) o; return Objects.equals(this.userId, orderStatus.userId) && Objects.equals(this.sessionId, orderStatus.sessionId) && Objects.equals(this.orderId, orderStatus.orderId) && Objects.equals(this.orderStatus, orderStatus.orderStatus) && Objects.equals(this.reason, orderStatus.reason) && Objects.equals(this.shippingCost, orderStatus.shippingCost) && Objects.equals(this.trackingNumber, orderStatus.trackingNumber) && Objects.equals(this.trackingMethod, orderStatus.trackingMethod) && Objects.equals(this.source, orderStatus.source) && Objects.equals(this.analyst, orderStatus.analyst) && Objects.equals(this.description, orderStatus.description) && Objects.equals(this.customInfo, orderStatus.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, orderId, orderStatus, reason, shippingCost, trackingNumber, trackingMethod, source, analyst, description, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderStatus {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" orderStatus: ").append(toIndentedString(orderStatus)).append("\n"); sb.append(" reason: ").append(toIndentedString(reason)).append("\n"); sb.append(" shippingCost: ").append(toIndentedString(shippingCost)).append("\n"); sb.append(" trackingNumber: ").append(toIndentedString(trackingNumber)).append("\n"); sb.append(" trackingMethod: ").append(toIndentedString(trackingMethod)).append("\n"); sb.append(" source: ").append(toIndentedString(source)).append("\n"); sb.append(" analyst: ").append(toIndentedString(analyst)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/PaymentMethod.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * The payment_method field type represents information about the payment methods provided by the user. The value must be a nested object with the appropriate item subfields for the given payment method. Generally usedwith the create_order or transaction events. */ @ApiModel(description = "The payment_method field type represents information about the payment methods provided by the user. The value must be a nested object with the appropriate item subfields for the given payment method. Generally usedwith the create_order or transaction events. ") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class PaymentMethod { @SerializedName("_paymentType") private String paymentType = null; @SerializedName("_amount") private String amount = null; @SerializedName("_currencyCode") private String currencyCode = null; @SerializedName("_paymentGateway") private String paymentGateway = null; @SerializedName("_accountName") private String accountName = null; @SerializedName("_cardBin") private String cardBin = null; @SerializedName("_avsResponseCode") private String avsResponseCode = null; @SerializedName("_cvvResponseCode") private String cvvResponseCode = null; @SerializedName("_cardLast4") private String cardLast4 = null; @SerializedName("_cardExpiryMonth") private String cardExpiryMonth = null; @SerializedName("_cardExpiryYear") private String cardExpiryYear = null; public PaymentMethod paymentType(String paymentType) { this.paymentType = paymentType; return this; } /** * Values like - _cash, _check, _creditCard, _debitCard, _netBanking, _wallet, _cryptoCurrency, _electronicFundTransfer, _financing, _giftCard, _interac, _invoice, _moneyOrder, _masterPass, _points, _storeCredit, _thirdPartyProcessor, _voucher * @return paymentType **/ @ApiModelProperty(value = "Values like - _cash, _check, _creditCard, _debitCard, _netBanking, _wallet, _cryptoCurrency, _electronicFundTransfer, _financing, _giftCard, _interac, _invoice, _moneyOrder, _masterPass, _points, _storeCredit, _thirdPartyProcessor, _voucher") public String getPaymentType() { return paymentType; } public void setPaymentType(String paymentType) { this.paymentType = paymentType; } public PaymentMethod amount(String amount) { this.amount = amount; return this; } /** * The item unit price in numbers, in the base unit of the currency_code.e.g. \&quot;2500\&quot;. In case of multiple payment methods in order it&#39;s useful. * @return amount **/ @ApiModelProperty(value = "The item unit price in numbers, in the base unit of the currency_code.e.g. \"2500\". In case of multiple payment methods in order it's useful.") public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public PaymentMethod currencyCode(String currencyCode) { this.currencyCode = currencyCode; return this; } /** * The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems. In case of multiple payment methods in order it&#39;s useful. * @return currencyCode **/ @ApiModelProperty(value = "The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems. In case of multiple payment methods in order it's useful.") public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public PaymentMethod paymentGateway(String paymentGateway) { this.paymentGateway = paymentGateway; return this; } /** * fill value like bank name, gateway name, wallet name etc, e.g. payu, paypal, icici, paytm * @return paymentGateway **/ @ApiModelProperty(value = "fill value like bank name, gateway name, wallet name etc, e.g. payu, paypal, icici, paytm") public String getPaymentGateway() { return paymentGateway; } public void setPaymentGateway(String paymentGateway) { this.paymentGateway = paymentGateway; } public PaymentMethod accountName(String accountName) { this.accountName = accountName; return this; } /** * Account name oif the user for that payment method * @return accountName **/ @ApiModelProperty(value = "Account name oif the user for that payment method") public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public PaymentMethod cardBin(String cardBin) { this.cardBin = cardBin; return this; } /** * The first six digits of the credit card number. These numbers contain information about the card issuer, the geography and other card details. * @return cardBin **/ @ApiModelProperty(value = "The first six digits of the credit card number. These numbers contain information about the card issuer, the geography and other card details.") public String getCardBin() { return cardBin; } public void setCardBin(String cardBin) { this.cardBin = cardBin; } public PaymentMethod avsResponseCode(String avsResponseCode) { this.avsResponseCode = avsResponseCode; return this; } /** * Response code from the AVS address verification system. Used in payments involving credit cards. * @return avsResponseCode **/ @ApiModelProperty(value = "Response code from the AVS address verification system. Used in payments involving credit cards.") public String getAvsResponseCode() { return avsResponseCode; } public void setAvsResponseCode(String avsResponseCode) { this.avsResponseCode = avsResponseCode; } public PaymentMethod cvvResponseCode(String cvvResponseCode) { this.cvvResponseCode = cvvResponseCode; return this; } /** * Response code from the credit card company indicating if the CVV number entered matches the number on record. Used in payments involving credit cards. * @return cvvResponseCode **/ @ApiModelProperty(value = "Response code from the credit card company indicating if the CVV number entered matches the number on record. Used in payments involving credit cards.") public String getCvvResponseCode() { return cvvResponseCode; } public void setCvvResponseCode(String cvvResponseCode) { this.cvvResponseCode = cvvResponseCode; } public PaymentMethod cardLast4(String cardLast4) { this.cardLast4 = cardLast4; return this; } /** * The last four digits of the credit card number. * @return cardLast4 **/ @ApiModelProperty(value = "The last four digits of the credit card number.") public String getCardLast4() { return cardLast4; } public void setCardLast4(String cardLast4) { this.cardLast4 = cardLast4; } public PaymentMethod cardExpiryMonth(String cardExpiryMonth) { this.cardExpiryMonth = cardExpiryMonth; return this; } /** * Expiry month of the card. * @return cardExpiryMonth **/ @ApiModelProperty(value = "Expiry month of the card.") public String getCardExpiryMonth() { return cardExpiryMonth; } public void setCardExpiryMonth(String cardExpiryMonth) { this.cardExpiryMonth = cardExpiryMonth; } public PaymentMethod cardExpiryYear(String cardExpiryYear) { this.cardExpiryYear = cardExpiryYear; return this; } /** * Expiry year of the card. * @return cardExpiryYear **/ @ApiModelProperty(value = "Expiry year of the card.") public String getCardExpiryYear() { return cardExpiryYear; } public void setCardExpiryYear(String cardExpiryYear) { this.cardExpiryYear = cardExpiryYear; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PaymentMethod paymentMethod = (PaymentMethod) o; return Objects.equals(this.paymentType, paymentMethod.paymentType) && Objects.equals(this.amount, paymentMethod.amount) && Objects.equals(this.currencyCode, paymentMethod.currencyCode) && Objects.equals(this.paymentGateway, paymentMethod.paymentGateway) && Objects.equals(this.accountName, paymentMethod.accountName) && Objects.equals(this.cardBin, paymentMethod.cardBin) && Objects.equals(this.avsResponseCode, paymentMethod.avsResponseCode) && Objects.equals(this.cvvResponseCode, paymentMethod.cvvResponseCode) && Objects.equals(this.cardLast4, paymentMethod.cardLast4) && Objects.equals(this.cardExpiryMonth, paymentMethod.cardExpiryMonth) && Objects.equals(this.cardExpiryYear, paymentMethod.cardExpiryYear); } @Override public int hashCode() { return Objects.hash(paymentType, amount, currencyCode, paymentGateway, accountName, cardBin, avsResponseCode, cvvResponseCode, cardLast4, cardExpiryMonth, cardExpiryYear); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PaymentMethod {\n"); sb.append(" paymentType: ").append(toIndentedString(paymentType)).append("\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" currencyCode: ").append(toIndentedString(currencyCode)).append("\n"); sb.append(" paymentGateway: ").append(toIndentedString(paymentGateway)).append("\n"); sb.append(" accountName: ").append(toIndentedString(accountName)).append("\n"); sb.append(" cardBin: ").append(toIndentedString(cardBin)).append("\n"); sb.append(" avsResponseCode: ").append(toIndentedString(avsResponseCode)).append("\n"); sb.append(" cvvResponseCode: ").append(toIndentedString(cvvResponseCode)).append("\n"); sb.append(" cardLast4: ").append(toIndentedString(cardLast4)).append("\n"); sb.append(" cardExpiryMonth: ").append(toIndentedString(cardExpiryMonth)).append("\n"); sb.append(" cardExpiryYear: ").append(toIndentedString(cardExpiryYear)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/Promotion.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * The Promotion field type generically models different kinds of promotions such as referrals, coupons, free trials, etc. The value must be a nested JSON object which you populate with the appropriate information to describe the promotion. Not all sub-fields will likely apply to a given promotion. Populate only those that apply. A promotion can be added when creating or updating an account, creating or updating an order, or on its own using the add_promotion event. The promotion object supports both monetary (e.g. 500 coupon on first order) and non-monetary (e.g. \&quot;100 in points to refer a friend\&quot;). */ @ApiModel(description = "The Promotion field type generically models different kinds of promotions such as referrals, coupons, free trials, etc. The value must be a nested JSON object which you populate with the appropriate information to describe the promotion. Not all sub-fields will likely apply to a given promotion. Populate only those that apply. A promotion can be added when creating or updating an account, creating or updating an order, or on its own using the add_promotion event. The promotion object supports both monetary (e.g. 500 coupon on first order) and non-monetary (e.g. \"100 in points to refer a friend\"). ") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class Promotion { @SerializedName("_promotionId") private String promotionId = null; @SerializedName("_status") private String status = null; @SerializedName("_description") private String description = null; @SerializedName("_amount") private String amount = null; @SerializedName("_minPurchaseAmount") private String minPurchaseAmount = null; @SerializedName("_referrerUserId") private String referrerUserId = null; @SerializedName("_failureReason") private String failureReason = null; @SerializedName("_percentageOff") private String percentageOff = null; @SerializedName("_currencyCode") private String currencyCode = null; @SerializedName("_type") private String type = null; public Promotion promotionId(String promotionId) { this.promotionId = promotionId; return this; } /** * The ID/Coupon Code within your system that you use to represent this promotion. This ID is ideally unique to the promotion across users (e.g. \&quot;Welcome\&quot;). * @return promotionId **/ @ApiModelProperty(value = "The ID/Coupon Code within your system that you use to represent this promotion. This ID is ideally unique to the promotion across users (e.g. \"Welcome\").") public String getPromotionId() { return promotionId; } public void setPromotionId(String promotionId) { this.promotionId = promotionId; } public Promotion status(String status) { this.status = status; return this; } /** * The status of the addition of promotion to an account. Best used with the add_promotion event. This way you can pass to Thirdwatch both successful and failed attempts when using a promotion. May be useful in spotting potential abuse. e.g. _success, _Failed * @return status **/ @ApiModelProperty(value = "The status of the addition of promotion to an account. Best used with the add_promotion event. This way you can pass to Thirdwatch both successful and failed attempts when using a promotion. May be useful in spotting potential abuse. e.g. _success, _Failed") public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Promotion description(String description) { this.description = description; return this; } /** * Describe promotion here. * @return description **/ @ApiModelProperty(value = "Describe promotion here.") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Promotion amount(String amount) { this.amount = amount; return this; } /** * The amount or credits the promotion is worth. * @return amount **/ @ApiModelProperty(value = "The amount or credits the promotion is worth.") public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public Promotion minPurchaseAmount(String minPurchaseAmount) { this.minPurchaseAmount = minPurchaseAmount; return this; } /** * The minimum amount someone must spend in order for the promotion to be applied. * @return minPurchaseAmount **/ @ApiModelProperty(value = "The minimum amount someone must spend in order for the promotion to be applied.") public String getMinPurchaseAmount() { return minPurchaseAmount; } public void setMinPurchaseAmount(String minPurchaseAmount) { this.minPurchaseAmount = minPurchaseAmount; } public Promotion referrerUserId(String referrerUserId) { this.referrerUserId = referrerUserId; return this; } /** * The unique user ID of the user who referred the user to this promotion. * @return referrerUserId **/ @ApiModelProperty(value = "The unique user ID of the user who referred the user to this promotion.") public String getReferrerUserId() { return referrerUserId; } public void setReferrerUserId(String referrerUserId) { this.referrerUserId = referrerUserId; } public Promotion failureReason(String failureReason) { this.failureReason = failureReason; return this; } /** * When adding a promotion fails, use this to describe why it failed.e.g. _alreadyUsed, _invalidCode, _notApplicable, _expired * @return failureReason **/ @ApiModelProperty(value = "When adding a promotion fails, use this to describe why it failed.e.g. _alreadyUsed, _invalidCode, _notApplicable, _expired") public String getFailureReason() { return failureReason; } public void setFailureReason(String failureReason) { this.failureReason = failureReason; } public Promotion percentageOff(String percentageOff) { this.percentageOff = percentageOff; return this; } /** * The percentage discount. If the discount is 10% off, you would send \&quot;10\&quot;. * @return percentageOff **/ @ApiModelProperty(value = "The percentage discount. If the discount is 10% off, you would send \"10\".") public String getPercentageOff() { return percentageOff; } public void setPercentageOff(String percentageOff) { this.percentageOff = percentageOff; } public Promotion currencyCode(String currencyCode) { this.currencyCode = currencyCode; return this; } /** * The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems. * @return currencyCode **/ @ApiModelProperty(value = "The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems.") public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public Promotion type(String type) { this.type = type; return this; } /** * Type of the promotion e.g., First Time, Refer, Diwali * @return type **/ @ApiModelProperty(value = "Type of the promotion e.g., First Time, Refer, Diwali") public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Promotion promotion = (Promotion) o; return Objects.equals(this.promotionId, promotion.promotionId) && Objects.equals(this.status, promotion.status) && Objects.equals(this.description, promotion.description) && Objects.equals(this.amount, promotion.amount) && Objects.equals(this.minPurchaseAmount, promotion.minPurchaseAmount) && Objects.equals(this.referrerUserId, promotion.referrerUserId) && Objects.equals(this.failureReason, promotion.failureReason) && Objects.equals(this.percentageOff, promotion.percentageOff) && Objects.equals(this.currencyCode, promotion.currencyCode) && Objects.equals(this.type, promotion.type); } @Override public int hashCode() { return Objects.hash(promotionId, status, description, amount, minPurchaseAmount, referrerUserId, failureReason, percentageOff, currencyCode, type); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Promotion {\n"); sb.append(" promotionId: ").append(toIndentedString(promotionId)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" minPurchaseAmount: ").append(toIndentedString(minPurchaseAmount)).append("\n"); sb.append(" referrerUserId: ").append(toIndentedString(referrerUserId)).append("\n"); sb.append(" failureReason: ").append(toIndentedString(failureReason)).append("\n"); sb.append(" percentageOff: ").append(toIndentedString(percentageOff)).append("\n"); sb.append(" currencyCode: ").append(toIndentedString(currencyCode)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/RemoveFromCart.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import ai.thirdwatch.model.Item; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * RemoveFromCart */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class RemoveFromCart { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_item") private Item item = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public RemoveFromCart userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public RemoveFromCart sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public RemoveFromCart deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public RemoveFromCart originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public RemoveFromCart item(Item item) { this.item = item; return this; } /** * Get item * @return item **/ @ApiModelProperty(value = "") public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } public RemoveFromCart customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RemoveFromCart removeFromCart = (RemoveFromCart) o; return Objects.equals(this.userId, removeFromCart.userId) && Objects.equals(this.sessionId, removeFromCart.sessionId) && Objects.equals(this.deviceIp, removeFromCart.deviceIp) && Objects.equals(this.originTimestamp, removeFromCart.originTimestamp) && Objects.equals(this.item, removeFromCart.item) && Objects.equals(this.customInfo, removeFromCart.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, deviceIp, originTimestamp, item, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class RemoveFromCart {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" item: ").append(toIndentedString(item)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/ReportItem.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * ReportItem */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class ReportItem { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_itemId") private String itemId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_userEmail") private String userEmail = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public ReportItem userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public ReportItem sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public ReportItem itemId(String itemId) { this.itemId = itemId; return this; } /** * The unique ID for the item that is being reported. Note - item IDs are case sensitive. * @return itemId **/ @ApiModelProperty(value = "The unique ID for the item that is being reported. Note - item IDs are case sensitive.") public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public ReportItem deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public ReportItem originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public ReportItem userEmail(String userEmail) { this.userEmail = userEmail; return this; } /** * Email of the user creating this order. Note - If the user&#39;s email is also their account ID in your system, set both the userId and userEmail fields to their email address. * @return userEmail **/ @ApiModelProperty(value = "Email of the user creating this order. Note - If the user's email is also their account ID in your system, set both the userId and userEmail fields to their email address.") public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public ReportItem customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ReportItem reportItem = (ReportItem) o; return Objects.equals(this.userId, reportItem.userId) && Objects.equals(this.sessionId, reportItem.sessionId) && Objects.equals(this.itemId, reportItem.itemId) && Objects.equals(this.deviceIp, reportItem.deviceIp) && Objects.equals(this.originTimestamp, reportItem.originTimestamp) && Objects.equals(this.userEmail, reportItem.userEmail) && Objects.equals(this.customInfo, reportItem.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, itemId, deviceIp, originTimestamp, userEmail, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ReportItem {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" itemId: ").append(toIndentedString(itemId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" userEmail: ").append(toIndentedString(userEmail)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/Seller.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * The Seller field type represents information about the seller. The value must be a nested object with the appropriate item subfields for the given seller. Generally usedwith the order, item or transaction events. */ @ApiModel(description = "The Seller field type represents information about the seller. The value must be a nested object with the appropriate item subfields for the given seller. Generally usedwith the order, item or transaction events. ") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class Seller { @SerializedName("_sellerId") private String sellerId = null; @SerializedName("_name") private String name = null; @SerializedName("_email") private String email = null; @SerializedName("_phone") private String phone = null; @SerializedName("_createdDate") private String createdDate = null; @SerializedName("_lastUpdatedDate") private String lastUpdatedDate = null; @SerializedName("_onboardingIpAddress") private String onboardingIpAddress = null; public Seller sellerId(String sellerId) { this.sellerId = sellerId; return this; } /** * The seller’s internal account ID. This field is required on all events required seller info. * @return sellerId **/ @ApiModelProperty(value = "The seller’s internal account ID. This field is required on all events required seller info.") public String getSellerId() { return sellerId; } public void setSellerId(String sellerId) { this.sellerId = sellerId; } public Seller name(String name) { this.name = name; return this; } /** * Provide the full name associated with the seller here. Concatenate first name and last name together if you collect them separately in your system. * @return name **/ @ApiModelProperty(value = "Provide the full name associated with the seller here. Concatenate first name and last name together if you collect them separately in your system.") public String getName() { return name; } public void setName(String name) { this.name = name; } public Seller email(String email) { this.email = email; return this; } /** * Email of the seller. Note - If the seller&#39;s email is also their account ID in your system, set both the _sellerId and _email fields to their email address. * @return email **/ @ApiModelProperty(value = "Email of the seller. Note - If the seller's email is also their account ID in your system, set both the _sellerId and _email fields to their email address.") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Seller phone(String phone) { this.phone = phone; return this; } /** * The primary phone number of the seller associated with this account. Provide the phone number as a string. * @return phone **/ @ApiModelProperty(value = "The primary phone number of the seller associated with this account. Provide the phone number as a string.") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Seller createdDate(String createdDate) { this.createdDate = createdDate; return this; } /** * Date when seller registered in system. * @return createdDate **/ @ApiModelProperty(value = "Date when seller registered in system.") public String getCreatedDate() { return createdDate; } public void setCreatedDate(String createdDate) { this.createdDate = createdDate; } public Seller lastUpdatedDate(String lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; return this; } /** * Date when seller profile uopdated last time. * @return lastUpdatedDate **/ @ApiModelProperty(value = "Date when seller profile uopdated last time.") public String getLastUpdatedDate() { return lastUpdatedDate; } public void setLastUpdatedDate(String lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; } public Seller onboardingIpAddress(String onboardingIpAddress) { this.onboardingIpAddress = onboardingIpAddress; return this; } /** * Ip address used by seller while registration. * @return onboardingIpAddress **/ @ApiModelProperty(value = "Ip address used by seller while registration.") public String getOnboardingIpAddress() { return onboardingIpAddress; } public void setOnboardingIpAddress(String onboardingIpAddress) { this.onboardingIpAddress = onboardingIpAddress; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Seller seller = (Seller) o; return Objects.equals(this.sellerId, seller.sellerId) && Objects.equals(this.name, seller.name) && Objects.equals(this.email, seller.email) && Objects.equals(this.phone, seller.phone) && Objects.equals(this.createdDate, seller.createdDate) && Objects.equals(this.lastUpdatedDate, seller.lastUpdatedDate) && Objects.equals(this.onboardingIpAddress, seller.onboardingIpAddress); } @Override public int hashCode() { return Objects.hash(sellerId, name, email, phone, createdDate, lastUpdatedDate, onboardingIpAddress); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Seller {\n"); sb.append(" sellerId: ").append(toIndentedString(sellerId)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" createdDate: ").append(toIndentedString(createdDate)).append("\n"); sb.append(" lastUpdatedDate: ").append(toIndentedString(lastUpdatedDate)).append("\n"); sb.append(" onboardingIpAddress: ").append(toIndentedString(onboardingIpAddress)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/SendMessage.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * SendMessage */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class SendMessage { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_recipientUserId") private String recipientUserId = null; @SerializedName("_subject") private String subject = null; @SerializedName("_content") private String content = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public SendMessage userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public SendMessage sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public SendMessage deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public SendMessage originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public SendMessage recipientUserId(String recipientUserId) { this.recipientUserId = recipientUserId; return this; } /** * _userID of the receiving user by default Store. * @return recipientUserId **/ @ApiModelProperty(value = "_userID of the receiving user by default Store.") public String getRecipientUserId() { return recipientUserId; } public void setRecipientUserId(String recipientUserId) { this.recipientUserId = recipientUserId; } public SendMessage subject(String subject) { this.subject = subject; return this; } /** * The subject of the message. * @return subject **/ @ApiModelProperty(value = "The subject of the message.") public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public SendMessage content(String content) { this.content = content; return this; } /** * The text content of the message. * @return content **/ @ApiModelProperty(value = "The text content of the message.") public String getContent() { return content; } public void setContent(String content) { this.content = content; } public SendMessage customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SendMessage sendMessage = (SendMessage) o; return Objects.equals(this.userId, sendMessage.userId) && Objects.equals(this.sessionId, sendMessage.sessionId) && Objects.equals(this.deviceIp, sendMessage.deviceIp) && Objects.equals(this.originTimestamp, sendMessage.originTimestamp) && Objects.equals(this.recipientUserId, sendMessage.recipientUserId) && Objects.equals(this.subject, sendMessage.subject) && Objects.equals(this.content, sendMessage.content) && Objects.equals(this.customInfo, sendMessage.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, deviceIp, originTimestamp, recipientUserId, subject, content, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SendMessage {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" recipientUserId: ").append(toIndentedString(recipientUserId)).append("\n"); sb.append(" subject: ").append(toIndentedString(subject)).append("\n"); sb.append(" content: ").append(toIndentedString(content)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/ShippingAddress.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * The Address field type represents a physical address. The value must be a nested object with the appropriate address subfields. We extract many geolocation features from these values. An address is represented as a nested JSON object. */ @ApiModel(description = "The Address field type represents a physical address. The value must be a nested object with the appropriate address subfields. We extract many geolocation features from these values. An address is represented as a nested JSON object. ") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class ShippingAddress { @SerializedName("_name") private String name = null; @SerializedName("_phone") private String phone = null; @SerializedName("_address1") private String address1 = null; @SerializedName("_address2") private String address2 = null; @SerializedName("_city") private String city = null; @SerializedName("_region") private String region = null; @SerializedName("_country") private String country = null; @SerializedName("_zipcode") private String zipcode = null; @SerializedName("_isOfficeAddress") private Boolean isOfficeAddress = null; @SerializedName("_isHomeAddress") private Boolean isHomeAddress = null; public ShippingAddress name(String name) { this.name = name; return this; } /** * Provide the full name associated with the address here. Concatenate first name and last name together if you collect them separately in your system. * @return name **/ @ApiModelProperty(value = "Provide the full name associated with the address here. Concatenate first name and last name together if you collect them separately in your system.") public String getName() { return name; } public void setName(String name) { this.name = name; } public ShippingAddress phone(String phone) { this.phone = phone; return this; } /** * The phone number associated with this address. Provide the phone number as a string starting with the country code. Use E.164 format or send in the standard national format of number&#39;s origin. * @return phone **/ @ApiModelProperty(value = "The phone number associated with this address. Provide the phone number as a string starting with the country code. Use E.164 format or send in the standard national format of number's origin.") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public ShippingAddress address1(String address1) { this.address1 = address1; return this; } /** * Address first line, e.g., \&quot;C802 Nirvana Courtyard\&quot;. * @return address1 **/ @ApiModelProperty(value = "Address first line, e.g., \"C802 Nirvana Courtyard\".") public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } public ShippingAddress address2(String address2) { this.address2 = address2; return this; } /** * Address second line, e.g., \&quot;Nirvana Country, Sector 50\&quot;. * @return address2 **/ @ApiModelProperty(value = "Address second line, e.g., \"Nirvana Country, Sector 50\".") public String getAddress2() { return address2; } public void setAddress2(String address2) { this.address2 = address2; } public ShippingAddress city(String city) { this.city = city; return this; } /** * The city or town name, e.g., \&quot;Gurgaon\&quot; . * @return city **/ @ApiModelProperty(value = "The city or town name, e.g., \"Gurgaon\" .") public String getCity() { return city; } public void setCity(String city) { this.city = city; } public ShippingAddress region(String region) { this.region = region; return this; } /** * The region portion of the address. In the India, this corresponds to the state. * @return region **/ @ApiModelProperty(value = "The region portion of the address. In the India, this corresponds to the state.") public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public ShippingAddress country(String country) { this.country = country; return this; } /** * The [ISO-3166](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code for the billing address, e.g., \&quot;IN\&quot; in case of India. * @return country **/ @ApiModelProperty(value = "The [ISO-3166](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code for the billing address, e.g., \"IN\" in case of India.") public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public ShippingAddress zipcode(String zipcode) { this.zipcode = zipcode; return this; } /** * The postal code associated with the address, e.g., \&quot;122002\&quot;. * @return zipcode **/ @ApiModelProperty(value = "The postal code associated with the address, e.g., \"122002\".") public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } public ShippingAddress isOfficeAddress(Boolean isOfficeAddress) { this.isOfficeAddress = isOfficeAddress; return this; } /** * Is user chosen this address as office address. * @return isOfficeAddress **/ @ApiModelProperty(value = "Is user chosen this address as office address.") public Boolean getIsOfficeAddress() { return isOfficeAddress; } public void setIsOfficeAddress(Boolean isOfficeAddress) { this.isOfficeAddress = isOfficeAddress; } public ShippingAddress isHomeAddress(Boolean isHomeAddress) { this.isHomeAddress = isHomeAddress; return this; } /** * Is user chosen this address as home address. * @return isHomeAddress **/ @ApiModelProperty(value = "Is user chosen this address as home address.") public Boolean getIsHomeAddress() { return isHomeAddress; } public void setIsHomeAddress(Boolean isHomeAddress) { this.isHomeAddress = isHomeAddress; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ShippingAddress shippingAddress = (ShippingAddress) o; return Objects.equals(this.name, shippingAddress.name) && Objects.equals(this.phone, shippingAddress.phone) && Objects.equals(this.address1, shippingAddress.address1) && Objects.equals(this.address2, shippingAddress.address2) && Objects.equals(this.city, shippingAddress.city) && Objects.equals(this.region, shippingAddress.region) && Objects.equals(this.country, shippingAddress.country) && Objects.equals(this.zipcode, shippingAddress.zipcode) && Objects.equals(this.isOfficeAddress, shippingAddress.isOfficeAddress) && Objects.equals(this.isHomeAddress, shippingAddress.isHomeAddress); } @Override public int hashCode() { return Objects.hash(name, phone, address1, address2, city, region, country, zipcode, isOfficeAddress, isHomeAddress); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ShippingAddress {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" address1: ").append(toIndentedString(address1)).append("\n"); sb.append(" address2: ").append(toIndentedString(address2)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" region: ").append(toIndentedString(region)).append("\n"); sb.append(" country: ").append(toIndentedString(country)).append("\n"); sb.append(" zipcode: ").append(toIndentedString(zipcode)).append("\n"); sb.append(" isOfficeAddress: ").append(toIndentedString(isOfficeAddress)).append("\n"); sb.append(" isHomeAddress: ").append(toIndentedString(isHomeAddress)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/SubmitReview.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * SubmitReview */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class SubmitReview { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_reviewTitle") private String reviewTitle = null; @SerializedName("_reviewContent") private String reviewContent = null; @SerializedName("_itemId") private String itemId = null; @SerializedName("_submissionStatus") private String submissionStatus = null; @SerializedName("_rating") private String rating = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public SubmitReview userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public SubmitReview sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public SubmitReview deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public SubmitReview originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public SubmitReview reviewTitle(String reviewTitle) { this.reviewTitle = reviewTitle; return this; } /** * The title of review submitted. * @return reviewTitle **/ @ApiModelProperty(value = "The title of review submitted.") public String getReviewTitle() { return reviewTitle; } public void setReviewTitle(String reviewTitle) { this.reviewTitle = reviewTitle; } public SubmitReview reviewContent(String reviewContent) { this.reviewContent = reviewContent; return this; } /** * The text content of review submitted. * @return reviewContent **/ @ApiModelProperty(value = "The text content of review submitted.") public String getReviewContent() { return reviewContent; } public void setReviewContent(String reviewContent) { this.reviewContent = reviewContent; } public SubmitReview itemId(String itemId) { this.itemId = itemId; return this; } /** * The ID of the product or service being reviewed. * @return itemId **/ @ApiModelProperty(value = "The ID of the product or service being reviewed.") public String getItemId() { return itemId; } public void setItemId(String itemId) { this.itemId = itemId; } public SubmitReview submissionStatus(String submissionStatus) { this.submissionStatus = submissionStatus; return this; } /** * If reviews in your system must be approved, use _submissionStatus to represent the status of the review. e.g. _success, _failure, _pending * @return submissionStatus **/ @ApiModelProperty(value = "If reviews in your system must be approved, use _submissionStatus to represent the status of the review. e.g. _success, _failure, _pending") public String getSubmissionStatus() { return submissionStatus; } public void setSubmissionStatus(String submissionStatus) { this.submissionStatus = submissionStatus; } public SubmitReview rating(String rating) { this.rating = rating; return this; } /** * The rating provided by the user. e.g. \&quot;4\&quot; * @return rating **/ @ApiModelProperty(value = "The rating provided by the user. e.g. \"4\"") public String getRating() { return rating; } public void setRating(String rating) { this.rating = rating; } public SubmitReview customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubmitReview submitReview = (SubmitReview) o; return Objects.equals(this.userId, submitReview.userId) && Objects.equals(this.sessionId, submitReview.sessionId) && Objects.equals(this.deviceIp, submitReview.deviceIp) && Objects.equals(this.originTimestamp, submitReview.originTimestamp) && Objects.equals(this.reviewTitle, submitReview.reviewTitle) && Objects.equals(this.reviewContent, submitReview.reviewContent) && Objects.equals(this.itemId, submitReview.itemId) && Objects.equals(this.submissionStatus, submitReview.submissionStatus) && Objects.equals(this.rating, submitReview.rating) && Objects.equals(this.customInfo, submitReview.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, deviceIp, originTimestamp, reviewTitle, reviewContent, itemId, submissionStatus, rating, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SubmitReview {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" reviewTitle: ").append(toIndentedString(reviewTitle)).append("\n"); sb.append(" reviewContent: ").append(toIndentedString(reviewContent)).append("\n"); sb.append(" itemId: ").append(toIndentedString(itemId)).append("\n"); sb.append(" submissionStatus: ").append(toIndentedString(submissionStatus)).append("\n"); sb.append(" rating: ").append(toIndentedString(rating)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/Tag.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Tag */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class Tag { @SerializedName("_userId") private String userId = null; @SerializedName("_isBad") private Boolean isBad = null; @SerializedName("_abuseType") private String abuseType = null; @SerializedName("_description") private String description = null; @SerializedName("_source") private String source = null; @SerializedName("_analyst") private String analyst = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public Tag userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Tag isBad(Boolean isBad) { this.isBad = isBad; return this; } /** * Indicates whether a user is engaging in behavior deemed harmful to your business. Set to true if the user is engaging in abusive activity. Set to false if the user is engaging in valid activity. * @return isBad **/ @ApiModelProperty(value = "Indicates whether a user is engaging in behavior deemed harmful to your business. Set to true if the user is engaging in abusive activity. Set to false if the user is engaging in valid activity.") public Boolean getIsBad() { return isBad; } public void setIsBad(Boolean isBad) { this.isBad = isBad; } public Tag abuseType(String abuseType) { this.abuseType = abuseType; return this; } /** * The type of abuse for which you want to send a tag. It&#39;s important to send a tag specific to the type of abuse the user is committing so that thirdwatch can learn about specific patterns of behavior. You&#39;ll end up with more accurate results this way. e.g. _paymentAbuse, _contentAbuse, _promotionAbuse, _accountAbuse * @return abuseType **/ @ApiModelProperty(value = "The type of abuse for which you want to send a tag. It's important to send a tag specific to the type of abuse the user is committing so that thirdwatch can learn about specific patterns of behavior. You'll end up with more accurate results this way. e.g. _paymentAbuse, _contentAbuse, _promotionAbuse, _accountAbuse") public String getAbuseType() { return abuseType; } public void setAbuseType(String abuseType) { this.abuseType = abuseType; } public Tag description(String description) { this.description = description; return this; } /** * The text content of the tag.Useful as annotation on why the label was added. * @return description **/ @ApiModelProperty(value = "The text content of the tag.Useful as annotation on why the label was added.") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Tag source(String source) { this.source = source; return this; } /** * String describing the original source of the tag information (e.g. payment gateway, manual review, etc.). * @return source **/ @ApiModelProperty(value = "String describing the original source of the tag information (e.g. payment gateway, manual review, etc.).") public String getSource() { return source; } public void setSource(String source) { this.source = source; } public Tag analyst(String analyst) { this.analyst = analyst; return this; } /** * Unique identifier (e.g. email address) of the analyst who applied the label. Useful for tracking purposes after the fact. * @return analyst **/ @ApiModelProperty(value = "Unique identifier (e.g. email address) of the analyst who applied the label. Useful for tracking purposes after the fact.") public String getAnalyst() { return analyst; } public void setAnalyst(String analyst) { this.analyst = analyst; } public Tag customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Tag tag = (Tag) o; return Objects.equals(this.userId, tag.userId) && Objects.equals(this.isBad, tag.isBad) && Objects.equals(this.abuseType, tag.abuseType) && Objects.equals(this.description, tag.description) && Objects.equals(this.source, tag.source) && Objects.equals(this.analyst, tag.analyst) && Objects.equals(this.customInfo, tag.customInfo); } @Override public int hashCode() { return Objects.hash(userId, isBad, abuseType, description, source, analyst, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Tag {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" isBad: ").append(toIndentedString(isBad)).append("\n"); sb.append(" abuseType: ").append(toIndentedString(abuseType)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" source: ").append(toIndentedString(source)).append("\n"); sb.append(" analyst: ").append(toIndentedString(analyst)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/Transaction.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.BillingAddress; import ai.thirdwatch.model.CustomInfo; import ai.thirdwatch.model.PaymentMethod; import ai.thirdwatch.model.ShippingAddress; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Transaction */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class Transaction { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_orderId") private String orderId = null; @SerializedName("_transactionId") private String transactionId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_userEmail") private String userEmail = null; @SerializedName("_amount") private String amount = null; @SerializedName("_currencyCode") private String currencyCode = null; @SerializedName("_transactionType") private String transactionType = null; @SerializedName("_transactionStatus") private String transactionStatus = null; @SerializedName("_isFirstTimeBuyer") private Boolean isFirstTimeBuyer = null; @SerializedName("_billingAddress") private BillingAddress billingAddress = null; @SerializedName("_shippingAddress") private ShippingAddress shippingAddress = null; @SerializedName("_paymentMethod") private PaymentMethod paymentMethod = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public Transaction userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Transaction sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public Transaction orderId(String orderId) { this.orderId = orderId; return this; } /** * The ID for tracking this order in your system. * @return orderId **/ @ApiModelProperty(required = true, value = "The ID for tracking this order in your system.") public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public Transaction transactionId(String transactionId) { this.transactionId = transactionId; return this; } /** * The ID for identifying this transaction. Important for tracking transactions, and linking different parts of the same transaction together, e.g., linking a refund to its original transaction. * @return transactionId **/ @ApiModelProperty(value = "The ID for identifying this transaction. Important for tracking transactions, and linking different parts of the same transaction together, e.g., linking a refund to its original transaction.") public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public Transaction deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public Transaction originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public Transaction userEmail(String userEmail) { this.userEmail = userEmail; return this; } /** * Email of the user creating this order. Note - If the user&#39;s email is also their account ID in your system, set both the userId and userEmail fields to their email address. * @return userEmail **/ @ApiModelProperty(value = "Email of the user creating this order. Note - If the user's email is also their account ID in your system, set both the userId and userEmail fields to their email address.") public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public Transaction amount(String amount) { this.amount = amount; return this; } /** * The item unit price in numbers, in the base unit of the currency_code.e.g. \&quot;2500\&quot; * @return amount **/ @ApiModelProperty(value = "The item unit price in numbers, in the base unit of the currency_code.e.g. \"2500\"") public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public Transaction currencyCode(String currencyCode) { this.currencyCode = currencyCode; return this; } /** * The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems. * @return currencyCode **/ @ApiModelProperty(value = "The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems.") public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public Transaction transactionType(String transactionType) { this.transactionType = transactionType; return this; } /** * The type of transaction being recorded. e.g. _sale, _authorize, _capture, _void, _refund, _deposit, _withdrawal, _transfer * @return transactionType **/ @ApiModelProperty(value = "The type of transaction being recorded. e.g. _sale, _authorize, _capture, _void, _refund, _deposit, _withdrawal, _transfer") public String getTransactionType() { return transactionType; } public void setTransactionType(String transactionType) { this.transactionType = transactionType; } public Transaction transactionStatus(String transactionStatus) { this.transactionStatus = transactionStatus; return this; } /** * Use _transactionStatus to indicate the status of the transaction. The value can be \&quot;_success\&quot; (default value), \&quot;_failure\&quot; or \&quot;_pending\&quot;. For instance, If the transaction was rejected by the payment gateway, set the value to \&quot;_failure\&quot;. * @return transactionStatus **/ @ApiModelProperty(required = true, value = "Use _transactionStatus to indicate the status of the transaction. The value can be \"_success\" (default value), \"_failure\" or \"_pending\". For instance, If the transaction was rejected by the payment gateway, set the value to \"_failure\".") public String getTransactionStatus() { return transactionStatus; } public void setTransactionStatus(String transactionStatus) { this.transactionStatus = transactionStatus; } public Transaction isFirstTimeBuyer(Boolean isFirstTimeBuyer) { this.isFirstTimeBuyer = isFirstTimeBuyer; return this; } /** * Is user first time buyer. * @return isFirstTimeBuyer **/ @ApiModelProperty(value = "Is user first time buyer.") public Boolean getIsFirstTimeBuyer() { return isFirstTimeBuyer; } public void setIsFirstTimeBuyer(Boolean isFirstTimeBuyer) { this.isFirstTimeBuyer = isFirstTimeBuyer; } public Transaction billingAddress(BillingAddress billingAddress) { this.billingAddress = billingAddress; return this; } /** * Get billingAddress * @return billingAddress **/ @ApiModelProperty(value = "") public BillingAddress getBillingAddress() { return billingAddress; } public void setBillingAddress(BillingAddress billingAddress) { this.billingAddress = billingAddress; } public Transaction shippingAddress(ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress; return this; } /** * Get shippingAddress * @return shippingAddress **/ @ApiModelProperty(value = "") public ShippingAddress getShippingAddress() { return shippingAddress; } public void setShippingAddress(ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress; } public Transaction paymentMethod(PaymentMethod paymentMethod) { this.paymentMethod = paymentMethod; return this; } /** * Get paymentMethod * @return paymentMethod **/ @ApiModelProperty(value = "") public PaymentMethod getPaymentMethod() { return paymentMethod; } public void setPaymentMethod(PaymentMethod paymentMethod) { this.paymentMethod = paymentMethod; } public Transaction customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Transaction transaction = (Transaction) o; return Objects.equals(this.userId, transaction.userId) && Objects.equals(this.sessionId, transaction.sessionId) && Objects.equals(this.orderId, transaction.orderId) && Objects.equals(this.transactionId, transaction.transactionId) && Objects.equals(this.deviceIp, transaction.deviceIp) && Objects.equals(this.originTimestamp, transaction.originTimestamp) && Objects.equals(this.userEmail, transaction.userEmail) && Objects.equals(this.amount, transaction.amount) && Objects.equals(this.currencyCode, transaction.currencyCode) && Objects.equals(this.transactionType, transaction.transactionType) && Objects.equals(this.transactionStatus, transaction.transactionStatus) && Objects.equals(this.isFirstTimeBuyer, transaction.isFirstTimeBuyer) && Objects.equals(this.billingAddress, transaction.billingAddress) && Objects.equals(this.shippingAddress, transaction.shippingAddress) && Objects.equals(this.paymentMethod, transaction.paymentMethod) && Objects.equals(this.customInfo, transaction.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, orderId, transactionId, deviceIp, originTimestamp, userEmail, amount, currencyCode, transactionType, transactionStatus, isFirstTimeBuyer, billingAddress, shippingAddress, paymentMethod, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Transaction {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" transactionId: ").append(toIndentedString(transactionId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" userEmail: ").append(toIndentedString(userEmail)).append("\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" currencyCode: ").append(toIndentedString(currencyCode)).append("\n"); sb.append(" transactionType: ").append(toIndentedString(transactionType)).append("\n"); sb.append(" transactionStatus: ").append(toIndentedString(transactionStatus)).append("\n"); sb.append(" isFirstTimeBuyer: ").append(toIndentedString(isFirstTimeBuyer)).append("\n"); sb.append(" billingAddress: ").append(toIndentedString(billingAddress)).append("\n"); sb.append(" shippingAddress: ").append(toIndentedString(shippingAddress)).append("\n"); sb.append(" paymentMethod: ").append(toIndentedString(paymentMethod)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/UnTag.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.CustomInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * UnTag */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class UnTag { @SerializedName("_userId") private String userId = null; @SerializedName("_abuseType") private String abuseType = null; @SerializedName("_analyst") private String analyst = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public UnTag userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public UnTag abuseType(String abuseType) { this.abuseType = abuseType; return this; } /** * The type of abuse for which you want to untag user. It&#39;s important to send a untag specific to the type of abuse. You&#39;ll end up with more accurate results this way. e.g. _paymentAbuse, _contentAbuse, _promotionAbuse, _accountAbuse If you wants to untag from all type of abuses than don&#39;t send this parameter. * @return abuseType **/ @ApiModelProperty(value = "The type of abuse for which you want to untag user. It's important to send a untag specific to the type of abuse. You'll end up with more accurate results this way. e.g. _paymentAbuse, _contentAbuse, _promotionAbuse, _accountAbuse If you wants to untag from all type of abuses than don't send this parameter.") public String getAbuseType() { return abuseType; } public void setAbuseType(String abuseType) { this.abuseType = abuseType; } public UnTag analyst(String analyst) { this.analyst = analyst; return this; } /** * Unique identifier (e.g. email address) of the analyst who applied the label. Useful for tracking purposes after the fact. * @return analyst **/ @ApiModelProperty(value = "Unique identifier (e.g. email address) of the analyst who applied the label. Useful for tracking purposes after the fact.") public String getAnalyst() { return analyst; } public void setAnalyst(String analyst) { this.analyst = analyst; } public UnTag customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UnTag unTag = (UnTag) o; return Objects.equals(this.userId, unTag.userId) && Objects.equals(this.abuseType, unTag.abuseType) && Objects.equals(this.analyst, unTag.analyst) && Objects.equals(this.customInfo, unTag.customInfo); } @Override public int hashCode() { return Objects.hash(userId, abuseType, analyst, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UnTag {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" abuseType: ").append(toIndentedString(abuseType)).append("\n"); sb.append(" analyst: ").append(toIndentedString(analyst)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/UpdateAccount.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.BillingAddress; import ai.thirdwatch.model.CustomInfo; import ai.thirdwatch.model.PaymentMethod; import ai.thirdwatch.model.Promotion; import ai.thirdwatch.model.ShippingAddress; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * UpdateAccount */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class UpdateAccount { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_userEmail") private String userEmail = null; @SerializedName("_firstName") private String firstName = null; @SerializedName("_lastName") private String lastName = null; @SerializedName("_phone") private String phone = null; @SerializedName("_age") private String age = null; @SerializedName("_gender") private String gender = null; @SerializedName("_referralCode") private String referralCode = null; @SerializedName("_referrerUserId") private String referrerUserId = null; @SerializedName("_billingAddress") private BillingAddress billingAddress = null; @SerializedName("_shippingAddress") private ShippingAddress shippingAddress = null; @SerializedName("_paymentMethods") private List<PaymentMethod> paymentMethods = null; @SerializedName("_promotions") private List<Promotion> promotions = null; @SerializedName("_socialSignOnType") private String socialSignOnType = null; @SerializedName("_emailConfirmedStatus") private String emailConfirmedStatus = null; @SerializedName("_phoneConfirmedStatus") private String phoneConfirmedStatus = null; @SerializedName("_isNewsletterSubscribed") private Boolean isNewsletterSubscribed = null; @SerializedName("_accountStatus") private String accountStatus = null; @SerializedName("_facebookId") private String facebookId = null; @SerializedName("_googleId") private String googleId = null; @SerializedName("_twitterId") private String twitterId = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public UpdateAccount userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public UpdateAccount sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public UpdateAccount deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public UpdateAccount originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public UpdateAccount userEmail(String userEmail) { this.userEmail = userEmail; return this; } /** * Email of the user creating this order. Note - If the user&#39;s email is also their account ID in your system, set both the userId and userEmail fields to their email address. * @return userEmail **/ @ApiModelProperty(value = "Email of the user creating this order. Note - If the user's email is also their account ID in your system, set both the userId and userEmail fields to their email address.") public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public UpdateAccount firstName(String firstName) { this.firstName = firstName; return this; } /** * Provide the first name associated with the user here. * @return firstName **/ @ApiModelProperty(value = "Provide the first name associated with the user here.") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public UpdateAccount lastName(String lastName) { this.lastName = lastName; return this; } /** * Provide the last name associated with the user here. * @return lastName **/ @ApiModelProperty(value = "Provide the last name associated with the user here.") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public UpdateAccount phone(String phone) { this.phone = phone; return this; } /** * The primary phone number of the user associated with this account. Provide the phone number as a string. * @return phone **/ @ApiModelProperty(value = "The primary phone number of the user associated with this account. Provide the phone number as a string.") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public UpdateAccount age(String age) { this.age = age; return this; } /** * Age of the user e.g. \&quot;25\&quot; * @return age **/ @ApiModelProperty(value = "Age of the user e.g. \"25\"") public String getAge() { return age; } public void setAge(String age) { this.age = age; } public UpdateAccount gender(String gender) { this.gender = gender; return this; } /** * Gender of the user e.g. \&quot;_male\&quot;, \&quot;_female\&quot; or \&quot;_trans\&quot; * @return gender **/ @ApiModelProperty(value = "Gender of the user e.g. \"_male\", \"_female\" or \"_trans\"") public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public UpdateAccount referralCode(String referralCode) { this.referralCode = referralCode; return this; } /** * Code or promotion used by the user while creating account. * @return referralCode **/ @ApiModelProperty(value = "Code or promotion used by the user while creating account.") public String getReferralCode() { return referralCode; } public void setReferralCode(String referralCode) { this.referralCode = referralCode; } public UpdateAccount referrerUserId(String referrerUserId) { this.referrerUserId = referrerUserId; return this; } /** * The ID of the user that referred the current user to your business. This field is required for detecting referral fraud. * @return referrerUserId **/ @ApiModelProperty(value = "The ID of the user that referred the current user to your business. This field is required for detecting referral fraud.") public String getReferrerUserId() { return referrerUserId; } public void setReferrerUserId(String referrerUserId) { this.referrerUserId = referrerUserId; } public UpdateAccount billingAddress(BillingAddress billingAddress) { this.billingAddress = billingAddress; return this; } /** * Get billingAddress * @return billingAddress **/ @ApiModelProperty(value = "") public BillingAddress getBillingAddress() { return billingAddress; } public void setBillingAddress(BillingAddress billingAddress) { this.billingAddress = billingAddress; } public UpdateAccount shippingAddress(ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress; return this; } /** * Get shippingAddress * @return shippingAddress **/ @ApiModelProperty(value = "") public ShippingAddress getShippingAddress() { return shippingAddress; } public void setShippingAddress(ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress; } public UpdateAccount paymentMethods(List<PaymentMethod> paymentMethods) { this.paymentMethods = paymentMethods; return this; } public UpdateAccount addPaymentMethodsItem(PaymentMethod paymentMethodsItem) { if (this.paymentMethods == null) { this.paymentMethods = new ArrayList<PaymentMethod>(); } this.paymentMethods.add(paymentMethodsItem); return this; } /** * The payment information associated with this account. Represented as an array of nested payment_method objects containing payment type, payment gateway, credit card bin, etc. * @return paymentMethods **/ @ApiModelProperty(value = "The payment information associated with this account. Represented as an array of nested payment_method objects containing payment type, payment gateway, credit card bin, etc.") public List<PaymentMethod> getPaymentMethods() { return paymentMethods; } public void setPaymentMethods(List<PaymentMethod> paymentMethods) { this.paymentMethods = paymentMethods; } public UpdateAccount promotions(List<Promotion> promotions) { this.promotions = promotions; return this; } public UpdateAccount addPromotionsItem(Promotion promotionsItem) { if (this.promotions == null) { this.promotions = new ArrayList<Promotion>(); } this.promotions.add(promotionsItem); return this; } /** * The list of promotions that apply to this account. You can add one or more promotions when creating or updating an order. Represented as a JSON array of promotion objects. You can also separately add promotions to the account via the addPromotion event. * @return promotions **/ @ApiModelProperty(value = "The list of promotions that apply to this account. You can add one or more promotions when creating or updating an order. Represented as a JSON array of promotion objects. You can also separately add promotions to the account via the addPromotion event.") public List<Promotion> getPromotions() { return promotions; } public void setPromotions(List<Promotion> promotions) { this.promotions = promotions; } public UpdateAccount socialSignOnType(String socialSignOnType) { this.socialSignOnType = socialSignOnType; return this; } /** * If the user logged in with a social identify provider, give the name here. e.g. _google, _facebook, _twitter, _linkedin, _other * @return socialSignOnType **/ @ApiModelProperty(value = "If the user logged in with a social identify provider, give the name here. e.g. _google, _facebook, _twitter, _linkedin, _other") public String getSocialSignOnType() { return socialSignOnType; } public void setSocialSignOnType(String socialSignOnType) { this.socialSignOnType = socialSignOnType; } public UpdateAccount emailConfirmedStatus(String emailConfirmedStatus) { this.emailConfirmedStatus = emailConfirmedStatus; return this; } /** * Status of email verification. e.g. _success, _failure, _pending * @return emailConfirmedStatus **/ @ApiModelProperty(value = "Status of email verification. e.g. _success, _failure, _pending") public String getEmailConfirmedStatus() { return emailConfirmedStatus; } public void setEmailConfirmedStatus(String emailConfirmedStatus) { this.emailConfirmedStatus = emailConfirmedStatus; } public UpdateAccount phoneConfirmedStatus(String phoneConfirmedStatus) { this.phoneConfirmedStatus = phoneConfirmedStatus; return this; } /** * Status of phone verification. e.g. _success, _failure, _pending * @return phoneConfirmedStatus **/ @ApiModelProperty(value = "Status of phone verification. e.g. _success, _failure, _pending") public String getPhoneConfirmedStatus() { return phoneConfirmedStatus; } public void setPhoneConfirmedStatus(String phoneConfirmedStatus) { this.phoneConfirmedStatus = phoneConfirmedStatus; } public UpdateAccount isNewsletterSubscribed(Boolean isNewsletterSubscribed) { this.isNewsletterSubscribed = isNewsletterSubscribed; return this; } /** * Is user subscribed for newsletter. e.g. true, false * @return isNewsletterSubscribed **/ @ApiModelProperty(value = "Is user subscribed for newsletter. e.g. true, false") public Boolean getIsNewsletterSubscribed() { return isNewsletterSubscribed; } public void setIsNewsletterSubscribed(Boolean isNewsletterSubscribed) { this.isNewsletterSubscribed = isNewsletterSubscribed; } public UpdateAccount accountStatus(String accountStatus) { this.accountStatus = accountStatus; return this; } /** * Current status of account, e.g. _active, _inactive * @return accountStatus **/ @ApiModelProperty(value = "Current status of account, e.g. _active, _inactive") public String getAccountStatus() { return accountStatus; } public void setAccountStatus(String accountStatus) { this.accountStatus = accountStatus; } public UpdateAccount facebookId(String facebookId) { this.facebookId = facebookId; return this; } /** * Facebook user id or token of the user. This can help to varify his social identity. * @return facebookId **/ @ApiModelProperty(value = "Facebook user id or token of the user. This can help to varify his social identity.") public String getFacebookId() { return facebookId; } public void setFacebookId(String facebookId) { this.facebookId = facebookId; } public UpdateAccount googleId(String googleId) { this.googleId = googleId; return this; } /** * Google user id or token of the user. This can help to varify his social identity. * @return googleId **/ @ApiModelProperty(value = "Google user id or token of the user. This can help to varify his social identity.") public String getGoogleId() { return googleId; } public void setGoogleId(String googleId) { this.googleId = googleId; } public UpdateAccount twitterId(String twitterId) { this.twitterId = twitterId; return this; } /** * Twitter handle or token of the user. This can help to varify his social identity. * @return twitterId **/ @ApiModelProperty(value = "Twitter handle or token of the user. This can help to varify his social identity.") public String getTwitterId() { return twitterId; } public void setTwitterId(String twitterId) { this.twitterId = twitterId; } public UpdateAccount customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UpdateAccount updateAccount = (UpdateAccount) o; return Objects.equals(this.userId, updateAccount.userId) && Objects.equals(this.sessionId, updateAccount.sessionId) && Objects.equals(this.deviceIp, updateAccount.deviceIp) && Objects.equals(this.originTimestamp, updateAccount.originTimestamp) && Objects.equals(this.userEmail, updateAccount.userEmail) && Objects.equals(this.firstName, updateAccount.firstName) && Objects.equals(this.lastName, updateAccount.lastName) && Objects.equals(this.phone, updateAccount.phone) && Objects.equals(this.age, updateAccount.age) && Objects.equals(this.gender, updateAccount.gender) && Objects.equals(this.referralCode, updateAccount.referralCode) && Objects.equals(this.referrerUserId, updateAccount.referrerUserId) && Objects.equals(this.billingAddress, updateAccount.billingAddress) && Objects.equals(this.shippingAddress, updateAccount.shippingAddress) && Objects.equals(this.paymentMethods, updateAccount.paymentMethods) && Objects.equals(this.promotions, updateAccount.promotions) && Objects.equals(this.socialSignOnType, updateAccount.socialSignOnType) && Objects.equals(this.emailConfirmedStatus, updateAccount.emailConfirmedStatus) && Objects.equals(this.phoneConfirmedStatus, updateAccount.phoneConfirmedStatus) && Objects.equals(this.isNewsletterSubscribed, updateAccount.isNewsletterSubscribed) && Objects.equals(this.accountStatus, updateAccount.accountStatus) && Objects.equals(this.facebookId, updateAccount.facebookId) && Objects.equals(this.googleId, updateAccount.googleId) && Objects.equals(this.twitterId, updateAccount.twitterId) && Objects.equals(this.customInfo, updateAccount.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, deviceIp, originTimestamp, userEmail, firstName, lastName, phone, age, gender, referralCode, referrerUserId, billingAddress, shippingAddress, paymentMethods, promotions, socialSignOnType, emailConfirmedStatus, phoneConfirmedStatus, isNewsletterSubscribed, accountStatus, facebookId, googleId, twitterId, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UpdateAccount {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" userEmail: ").append(toIndentedString(userEmail)).append("\n"); sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" age: ").append(toIndentedString(age)).append("\n"); sb.append(" gender: ").append(toIndentedString(gender)).append("\n"); sb.append(" referralCode: ").append(toIndentedString(referralCode)).append("\n"); sb.append(" referrerUserId: ").append(toIndentedString(referrerUserId)).append("\n"); sb.append(" billingAddress: ").append(toIndentedString(billingAddress)).append("\n"); sb.append(" shippingAddress: ").append(toIndentedString(shippingAddress)).append("\n"); sb.append(" paymentMethods: ").append(toIndentedString(paymentMethods)).append("\n"); sb.append(" promotions: ").append(toIndentedString(promotions)).append("\n"); sb.append(" socialSignOnType: ").append(toIndentedString(socialSignOnType)).append("\n"); sb.append(" emailConfirmedStatus: ").append(toIndentedString(emailConfirmedStatus)).append("\n"); sb.append(" phoneConfirmedStatus: ").append(toIndentedString(phoneConfirmedStatus)).append("\n"); sb.append(" isNewsletterSubscribed: ").append(toIndentedString(isNewsletterSubscribed)).append("\n"); sb.append(" accountStatus: ").append(toIndentedString(accountStatus)).append("\n"); sb.append(" facebookId: ").append(toIndentedString(facebookId)).append("\n"); sb.append(" googleId: ").append(toIndentedString(googleId)).append("\n"); sb.append(" twitterId: ").append(toIndentedString(twitterId)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch
java-sources/ai/thirdwatch/thirdwatch_api/0.0.2/ai/thirdwatch/model/UpdateOrder.java
/* * Thirdwatch API * The first version of the Thirdwatch API is an exciting step forward towards making it easier for developers to pass data to Thirdwatch. Once you've [registered your website/app](https://thirdwatch.ai) it's easy to start sending data to Thirdwatch. All endpoints are only accessible via https and are located at `api.thirdwatch.ai`. For instance: you can send event at the moment by ```HTTP POST``` Request to the following URL with your API key in ```Header``` and ```JSON``` data in request body. ``` https://api.thirdwatch.ai/event/v1 ``` Every API request must contain ```API Key``` in header value ```X-THIRDWATCH-API-KEY``` Every event must contain your ```_userId``` (if this is not available, you can alternatively provide a ```_sessionId``` value also in ```_userId```). JavaScript Fingerprinting module for capturing unique devices and tracking user interaction. This script will identify unique devices with respect to the browser. For e.g., if chrome is opened in normal mode a unique device id is generated and this will be same if chrome is opened in incognito mode or reinstalled. Paste the below script onto your webpage, just after the opening `<body>` tag. This script should be added to the page which is accessed externally by the user of your website. For e.g., If you want to track three different webpages then paste the below script onto each webpage, just after the opening `<body>` tag. This script should not be added onto internal tools or admin panels. ``` &lt;script id=\"thirdwatch\" data-session-cookie-name=\"&lt;cookie_name&gt;\" data-session-id-value=\"&lt;session_id&gt;\" data-user-id=\"&lt;user_id&gt;\" data-app-secret=\"&lt;app_secret&gt;\" data-is-track-pageview=\"true\"&gt; (function() { var loadDeviceJs = function() { var element = document.createElement(\"script\"); element.async = 1; element.src = \"https://cdn.thirdwatch.ai/tw.min.js\"; document.body.appendChild(element); }; if (window.addEventListener) { window.addEventListener(\"load\", loadDeviceJs, false); } else if (window.attachEvent) { window.attachEvent(\"onload\", loadDeviceJs); } })(); &lt;/script&gt; ``` * `data-session-cookie-name` -- The cookie name where you are saving the unique session id. We will pick the session id by reading its value from the cookie name. (Optional) * `data-session-id-value` -- In case you are not passing `data-session-cookie-name` than you can put session id directly in this parameter. In absence of both `data-session-cookie-name` and `data-session-id-value`, our system will generate a session Id. (Optional) * `data-user-id` -- Unique user id at your end. This can be email id or primary key in the database. In case of guest user, you can insert session Id here. * `data-app-secret` -- Unique App secret generated for you by Thirdwatch. * `data-is-track-pageview` -- If this is set to true, then the url on which this script is running will be sent to Thirdwatch, else the url will not be captured. The Score API is use to get an up to date cutomer trust score after you have sent transaction event and order successful. This API will provide the riskiness score of the order with reasons. Some examples of when you may want to check the score are before: - Before Shippement of a package - Finalizing a money transfer - Giving access to a prearranged vacation rental - Sending voucher on mail ``` https://api.thirdwatch.ai/neo/v1/score?api_key=<your api key>&order_id=<Order id> ``` According to Score you can decide to take action Approve or Reject. Orders with score more than 70 will consider as Riskey orders. We'll provide some reasons also in rules section. ``` { \"order_id\": \"OCT45671\", \"user_id\": \"ajay_245\", \"order_timestamp\": \"2017-05-09T09:40:45.717Z\", \"score\": 82, \"flag\": \"red\", -\"reasons\": [ { \"name\": \"_numOfFailedTransactions\", \"display_name\": \"Number of failed transactions\", \"flag\": \"green\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_accountAge\", \"display_name\": \"Account age\", \"flag\": \"red\", \"value\": \"0\", \"is_display\": true }, { \"name\": \"_numOfOrderSameIp\", \"display_name\": \"Number of orders from same IP\", \"flag\": \"red\", \"value\": \"11\", \"is_display\": true } ] } ``` * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package ai.thirdwatch.model; import java.util.Objects; import ai.thirdwatch.model.BillingAddress; import ai.thirdwatch.model.CustomInfo; import ai.thirdwatch.model.Item; import ai.thirdwatch.model.PaymentMethod; import ai.thirdwatch.model.Promotion; import ai.thirdwatch.model.ShippingAddress; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * UpdateOrder */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-11-21T16:23:00.366+05:30") public class UpdateOrder { @SerializedName("_userId") private String userId = null; @SerializedName("_sessionId") private String sessionId = null; @SerializedName("_orderId") private String orderId = null; @SerializedName("_deviceIp") private String deviceIp = null; @SerializedName("_originTimestamp") private String originTimestamp = null; @SerializedName("_userEmail") private String userEmail = null; @SerializedName("_amount") private String amount = null; @SerializedName("_currencyCode") private String currencyCode = null; @SerializedName("_hasExpeditedShipping") private Boolean hasExpeditedShipping = null; @SerializedName("_shippingMethod") private String shippingMethod = null; @SerializedName("_orderReferrer") private String orderReferrer = null; @SerializedName("_isPrePaid") private Boolean isPrePaid = null; @SerializedName("_isGift") private Boolean isGift = null; @SerializedName("_isReturn") private Boolean isReturn = null; @SerializedName("_isFirstTimeBuyer") private Boolean isFirstTimeBuyer = null; @SerializedName("_billingAddress") private BillingAddress billingAddress = null; @SerializedName("_shippingAddress") private ShippingAddress shippingAddress = null; @SerializedName("_paymentMethods") private List<PaymentMethod> paymentMethods = null; @SerializedName("_promotions") private List<Promotion> promotions = null; @SerializedName("_items") private List<Item> items = null; @SerializedName("_customInfo") private CustomInfo customInfo = null; public UpdateOrder userId(String userId) { this.userId = userId; return this; } /** * The user&#39;s account ID according to your systems. Note that user IDs are case sensitive. * @return userId **/ @ApiModelProperty(value = "The user's account ID according to your systems. Note that user IDs are case sensitive.") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public UpdateOrder sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * The user&#39;s current session ID, used to tie a user&#39;s action before and after login or account creation. Required if no user_id values is provided. * @return sessionId **/ @ApiModelProperty(value = "The user's current session ID, used to tie a user's action before and after login or account creation. Required if no user_id values is provided.") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public UpdateOrder orderId(String orderId) { this.orderId = orderId; return this; } /** * The ID for tracking this order in your system. * @return orderId **/ @ApiModelProperty(required = true, value = "The ID for tracking this order in your system.") public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public UpdateOrder deviceIp(String deviceIp) { this.deviceIp = deviceIp; return this; } /** * IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps. * @return deviceIp **/ @ApiModelProperty(value = "IP address of the request made by the user. Recommended for historical backfills and customers with mobile apps.") public String getDeviceIp() { return deviceIp; } public void setDeviceIp(String deviceIp) { this.deviceIp = deviceIp; } public UpdateOrder originTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; return this; } /** * Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string. * @return originTimestamp **/ @ApiModelProperty(value = "Represents the time the event occured in your system. Send as a UNIX timestamp in milliseconds in string.") public String getOriginTimestamp() { return originTimestamp; } public void setOriginTimestamp(String originTimestamp) { this.originTimestamp = originTimestamp; } public UpdateOrder userEmail(String userEmail) { this.userEmail = userEmail; return this; } /** * Email of the user creating this order. Note - If the user&#39;s email is also their account ID in your system, set both the userId and userEmail fields to their email address. * @return userEmail **/ @ApiModelProperty(value = "Email of the user creating this order. Note - If the user's email is also their account ID in your system, set both the userId and userEmail fields to their email address.") public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public UpdateOrder amount(String amount) { this.amount = amount; return this; } /** * The item unit price in numbers, in the base unit of the currency_code.e.g. \&quot;2500\&quot; * @return amount **/ @ApiModelProperty(value = "The item unit price in numbers, in the base unit of the currency_code.e.g. \"2500\"") public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public UpdateOrder currencyCode(String currencyCode) { this.currencyCode = currencyCode; return this; } /** * The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems. * @return currencyCode **/ @ApiModelProperty(value = "The [ISO-4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for the amount. e.g., USD, INR alternative currencies, like bitcoin or points systems.") public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public UpdateOrder hasExpeditedShipping(Boolean hasExpeditedShipping) { this.hasExpeditedShipping = hasExpeditedShipping; return this; } /** * Whether the user requested priority/expedited shipping on their order. * @return hasExpeditedShipping **/ @ApiModelProperty(value = "Whether the user requested priority/expedited shipping on their order.") public Boolean getHasExpeditedShipping() { return hasExpeditedShipping; } public void setHasExpeditedShipping(Boolean hasExpeditedShipping) { this.hasExpeditedShipping = hasExpeditedShipping; } public UpdateOrder shippingMethod(String shippingMethod) { this.shippingMethod = shippingMethod; return this; } /** * Indicates the method of delivery to the user. e.g. _electronic, _physical * @return shippingMethod **/ @ApiModelProperty(value = "Indicates the method of delivery to the user. e.g. _electronic, _physical") public String getShippingMethod() { return shippingMethod; } public void setShippingMethod(String shippingMethod) { this.shippingMethod = shippingMethod; } public UpdateOrder orderReferrer(String orderReferrer) { this.orderReferrer = orderReferrer; return this; } /** * Referer website or user name. * @return orderReferrer **/ @ApiModelProperty(value = "Referer website or user name.") public String getOrderReferrer() { return orderReferrer; } public void setOrderReferrer(String orderReferrer) { this.orderReferrer = orderReferrer; } public UpdateOrder isPrePaid(Boolean isPrePaid) { this.isPrePaid = isPrePaid; return this; } /** * is order is prepaid. * @return isPrePaid **/ @ApiModelProperty(value = "is order is prepaid.") public Boolean getIsPrePaid() { return isPrePaid; } public void setIsPrePaid(Boolean isPrePaid) { this.isPrePaid = isPrePaid; } public UpdateOrder isGift(Boolean isGift) { this.isGift = isGift; return this; } /** * Is user chosen gift pack. * @return isGift **/ @ApiModelProperty(value = "Is user chosen gift pack.") public Boolean getIsGift() { return isGift; } public void setIsGift(Boolean isGift) { this.isGift = isGift; } public UpdateOrder isReturn(Boolean isReturn) { this.isReturn = isReturn; return this; } /** * Is this return order. * @return isReturn **/ @ApiModelProperty(value = "Is this return order.") public Boolean getIsReturn() { return isReturn; } public void setIsReturn(Boolean isReturn) { this.isReturn = isReturn; } public UpdateOrder isFirstTimeBuyer(Boolean isFirstTimeBuyer) { this.isFirstTimeBuyer = isFirstTimeBuyer; return this; } /** * Is user first time buyer. * @return isFirstTimeBuyer **/ @ApiModelProperty(value = "Is user first time buyer.") public Boolean getIsFirstTimeBuyer() { return isFirstTimeBuyer; } public void setIsFirstTimeBuyer(Boolean isFirstTimeBuyer) { this.isFirstTimeBuyer = isFirstTimeBuyer; } public UpdateOrder billingAddress(BillingAddress billingAddress) { this.billingAddress = billingAddress; return this; } /** * Get billingAddress * @return billingAddress **/ @ApiModelProperty(value = "") public BillingAddress getBillingAddress() { return billingAddress; } public void setBillingAddress(BillingAddress billingAddress) { this.billingAddress = billingAddress; } public UpdateOrder shippingAddress(ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress; return this; } /** * Get shippingAddress * @return shippingAddress **/ @ApiModelProperty(value = "") public ShippingAddress getShippingAddress() { return shippingAddress; } public void setShippingAddress(ShippingAddress shippingAddress) { this.shippingAddress = shippingAddress; } public UpdateOrder paymentMethods(List<PaymentMethod> paymentMethods) { this.paymentMethods = paymentMethods; return this; } public UpdateOrder addPaymentMethodsItem(PaymentMethod paymentMethodsItem) { if (this.paymentMethods == null) { this.paymentMethods = new ArrayList<PaymentMethod>(); } this.paymentMethods.add(paymentMethodsItem); return this; } /** * The payment information associated with this order. Represented as an array of nested payment_method objects containing payment type, payment gateway, credit card bin, etc. * @return paymentMethods **/ @ApiModelProperty(value = "The payment information associated with this order. Represented as an array of nested payment_method objects containing payment type, payment gateway, credit card bin, etc.") public List<PaymentMethod> getPaymentMethods() { return paymentMethods; } public void setPaymentMethods(List<PaymentMethod> paymentMethods) { this.paymentMethods = paymentMethods; } public UpdateOrder promotions(List<Promotion> promotions) { this.promotions = promotions; return this; } public UpdateOrder addPromotionsItem(Promotion promotionsItem) { if (this.promotions == null) { this.promotions = new ArrayList<Promotion>(); } this.promotions.add(promotionsItem); return this; } /** * The list of promotions that apply to this order. You can add one or more promotions when creating or updating an order. Represented as a JSON array of promotion objects. You can also separately add promotions to the account via the addPromotion event. * @return promotions **/ @ApiModelProperty(value = "The list of promotions that apply to this order. You can add one or more promotions when creating or updating an order. Represented as a JSON array of promotion objects. You can also separately add promotions to the account via the addPromotion event.") public List<Promotion> getPromotions() { return promotions; } public void setPromotions(List<Promotion> promotions) { this.promotions = promotions; } public UpdateOrder items(List<Item> items) { this.items = items; return this; } public UpdateOrder addItemsItem(Item itemsItem) { if (this.items == null) { this.items = new ArrayList<Item>(); } this.items.add(itemsItem); return this; } /** * The list of items ordered. Represented as a JSON array of item * @return items **/ @ApiModelProperty(value = "The list of items ordered. Represented as a JSON array of item") public List<Item> getItems() { return items; } public void setItems(List<Item> items) { this.items = items; } public UpdateOrder customInfo(CustomInfo customInfo) { this.customInfo = customInfo; return this; } /** * Get customInfo * @return customInfo **/ @ApiModelProperty(value = "") public CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(CustomInfo customInfo) { this.customInfo = customInfo; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UpdateOrder updateOrder = (UpdateOrder) o; return Objects.equals(this.userId, updateOrder.userId) && Objects.equals(this.sessionId, updateOrder.sessionId) && Objects.equals(this.orderId, updateOrder.orderId) && Objects.equals(this.deviceIp, updateOrder.deviceIp) && Objects.equals(this.originTimestamp, updateOrder.originTimestamp) && Objects.equals(this.userEmail, updateOrder.userEmail) && Objects.equals(this.amount, updateOrder.amount) && Objects.equals(this.currencyCode, updateOrder.currencyCode) && Objects.equals(this.hasExpeditedShipping, updateOrder.hasExpeditedShipping) && Objects.equals(this.shippingMethod, updateOrder.shippingMethod) && Objects.equals(this.orderReferrer, updateOrder.orderReferrer) && Objects.equals(this.isPrePaid, updateOrder.isPrePaid) && Objects.equals(this.isGift, updateOrder.isGift) && Objects.equals(this.isReturn, updateOrder.isReturn) && Objects.equals(this.isFirstTimeBuyer, updateOrder.isFirstTimeBuyer) && Objects.equals(this.billingAddress, updateOrder.billingAddress) && Objects.equals(this.shippingAddress, updateOrder.shippingAddress) && Objects.equals(this.paymentMethods, updateOrder.paymentMethods) && Objects.equals(this.promotions, updateOrder.promotions) && Objects.equals(this.items, updateOrder.items) && Objects.equals(this.customInfo, updateOrder.customInfo); } @Override public int hashCode() { return Objects.hash(userId, sessionId, orderId, deviceIp, originTimestamp, userEmail, amount, currencyCode, hasExpeditedShipping, shippingMethod, orderReferrer, isPrePaid, isGift, isReturn, isFirstTimeBuyer, billingAddress, shippingAddress, paymentMethods, promotions, items, customInfo); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UpdateOrder {\n"); sb.append(" userId: ").append(toIndentedString(userId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" deviceIp: ").append(toIndentedString(deviceIp)).append("\n"); sb.append(" originTimestamp: ").append(toIndentedString(originTimestamp)).append("\n"); sb.append(" userEmail: ").append(toIndentedString(userEmail)).append("\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" currencyCode: ").append(toIndentedString(currencyCode)).append("\n"); sb.append(" hasExpeditedShipping: ").append(toIndentedString(hasExpeditedShipping)).append("\n"); sb.append(" shippingMethod: ").append(toIndentedString(shippingMethod)).append("\n"); sb.append(" orderReferrer: ").append(toIndentedString(orderReferrer)).append("\n"); sb.append(" isPrePaid: ").append(toIndentedString(isPrePaid)).append("\n"); sb.append(" isGift: ").append(toIndentedString(isGift)).append("\n"); sb.append(" isReturn: ").append(toIndentedString(isReturn)).append("\n"); sb.append(" isFirstTimeBuyer: ").append(toIndentedString(isFirstTimeBuyer)).append("\n"); sb.append(" billingAddress: ").append(toIndentedString(billingAddress)).append("\n"); sb.append(" shippingAddress: ").append(toIndentedString(shippingAddress)).append("\n"); sb.append(" paymentMethods: ").append(toIndentedString(paymentMethods)).append("\n"); sb.append(" promotions: ").append(toIndentedString(promotions)).append("\n"); sb.append(" items: ").append(toIndentedString(items)).append("\n"); sb.append(" customInfo: ").append(toIndentedString(customInfo)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/AnnotationMetadata.java
package ai.timefold.jpyinterpreter; import java.lang.annotation.Annotation; import java.lang.annotation.Repeatable; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; public record AnnotationMetadata(@NonNull Class<? extends Annotation> annotationType, @NonNull Map<String, Object> annotationValueMap, @Nullable Class<?> fieldTypeOverride) { public void addAnnotationTo(ClassVisitor classVisitor) { visitAnnotation(classVisitor.visitAnnotation(Type.getDescriptor(annotationType), true)); } public void addAnnotationTo(FieldVisitor fieldVisitor) { visitAnnotation(fieldVisitor.visitAnnotation(Type.getDescriptor(annotationType), true)); } public void addAnnotationTo(MethodVisitor methodVisitor) { visitAnnotation(methodVisitor.visitAnnotation(Type.getDescriptor(annotationType), true)); } public static List<AnnotationMetadata> getAnnotationListWithoutRepeatable(List<AnnotationMetadata> metadata) { List<AnnotationMetadata> out = new ArrayList<>(); Map<Class<? extends Annotation>, List<AnnotationMetadata>> repeatableAnnotationMap = new LinkedHashMap<>(); Map<Class<? extends Annotation>, Class<?>> fieldTypeOverrideMap = new LinkedHashMap<>(); for (AnnotationMetadata annotation : metadata) { Repeatable repeatable = annotation.annotationType().getAnnotation(Repeatable.class); if (repeatable == null) { out.add(annotation); continue; } var annotationContainer = repeatable.value(); fieldTypeOverrideMap.put(annotationContainer, annotation.fieldTypeOverride()); repeatableAnnotationMap.computeIfAbsent(annotationContainer, ignored -> new ArrayList<>()).add(annotation); } for (var entry : repeatableAnnotationMap.entrySet()) { out.add(new AnnotationMetadata(entry.getKey(), Map.of("value", entry.getValue().toArray(AnnotationMetadata[]::new)), fieldTypeOverrideMap.get(entry.getKey()))); } return out; } public static Type getValueAsType(String className) { return Type.getType("L" + className.replace('.', '/') + ";"); } private void visitAnnotation(AnnotationVisitor annotationVisitor) { for (var entry : annotationValueMap.entrySet()) { var annotationAttributeName = entry.getKey(); var annotationAttributeValue = entry.getValue(); visitAnnotationAttribute(annotationVisitor, annotationAttributeName, annotationAttributeValue); } annotationVisitor.visitEnd(); } private void visitAnnotationAttribute(AnnotationVisitor annotationVisitor, String attributeName, Object attributeValue) { if (attributeValue instanceof Number || attributeValue instanceof Boolean || attributeValue instanceof Character || attributeValue instanceof String) { annotationVisitor.visit(attributeName, attributeValue); return; } if (attributeValue instanceof Type type) { annotationVisitor.visit(attributeName, type); return; } if (attributeValue instanceof AnnotationMetadata annotationMetadata) { annotationMetadata.visitAnnotation( annotationVisitor.visitAnnotation(attributeName, Type.getDescriptor(annotationMetadata.annotationType))); return; } if (attributeValue instanceof Enum<?> enumValue) { annotationVisitor.visitEnum(attributeName, Type.getDescriptor(enumValue.getClass()), enumValue.name()); return; } if (attributeValue.getClass().isArray()) { var arrayAnnotationVisitor = annotationVisitor.visitArray(attributeName); var arrayLength = Array.getLength(attributeValue); for (int i = 0; i < arrayLength; i++) { visitAnnotationAttribute(arrayAnnotationVisitor, attributeName, Array.get(attributeValue, i)); } arrayAnnotationVisitor.visitEnd(); return; } throw new IllegalArgumentException("Annotation of type %s has an illegal value %s for attribute %s." .formatted(annotationType, attributeValue, attributeName)); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/BytecodeSwitchImplementor.java
package ai.timefold.jpyinterpreter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.function.Consumer; import java.util.stream.Collectors; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class BytecodeSwitchImplementor { public static void createStringSwitch(MethodVisitor methodVisitor, Collection<String> keyNames, int switchVariable, Consumer<String> caseWriter, Runnable defaultCase, boolean doesEachCaseReturnEarly) { if (keyNames.isEmpty()) { defaultCase.run(); return; } // keys in lookup switch MUST be sorted SortedMap<Integer, List<String>> hashCodeToMatchingFieldList = new TreeMap<>(); for (String fieldName : keyNames) { hashCodeToMatchingFieldList.computeIfAbsent(fieldName.hashCode(), hash -> new ArrayList<>()).add(fieldName); } int[] keys = new int[hashCodeToMatchingFieldList.size()]; Label[] hashCodeLabels = new Label[keys.length]; { // Scoped to hide keyIndex int keyIndex = 0; for (Integer key : hashCodeToMatchingFieldList.keySet()) { keys[keyIndex] = key; hashCodeLabels[keyIndex] = new Label(); keyIndex++; } } final int TOS_VARIABLE = switchVariable; final int CASE_VARIABLE = TOS_VARIABLE + 1; methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ASTORE, TOS_VARIABLE); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(String.class), "hashCode", Type.getMethodDescriptor(Type.INT_TYPE), false); Map<Integer, String> switchVariableValueToField = new HashMap<>(); Label endOfKeySwitch = new Label(); methodVisitor.visitLdcInsn(-1); methodVisitor.visitVarInsn(Opcodes.ISTORE, CASE_VARIABLE); methodVisitor.visitLookupSwitchInsn(endOfKeySwitch, keys, hashCodeLabels); int totalEntries = 0; for (int i = 0; i < keys.length; i++) { methodVisitor.visitLabel(hashCodeLabels[i]); List<String> matchingFields = hashCodeToMatchingFieldList.get(keys[i]); for (int fieldIndex = 0; fieldIndex < matchingFields.size(); fieldIndex++) { String field = matchingFields.get(fieldIndex); Label ifDoesNotMatchLabel = new Label(); methodVisitor.visitVarInsn(Opcodes.ALOAD, TOS_VARIABLE); methodVisitor.visitLdcInsn(field); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(String.class), "equals", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), false); if (fieldIndex != matchingFields.size() - 1) { methodVisitor.visitJumpInsn(Opcodes.IFEQ, ifDoesNotMatchLabel); } else { methodVisitor.visitJumpInsn(Opcodes.IFEQ, endOfKeySwitch); } methodVisitor.visitLdcInsn(totalEntries); methodVisitor.visitVarInsn(Opcodes.ISTORE, CASE_VARIABLE); if (fieldIndex != matchingFields.size() - 1) { methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfKeySwitch); methodVisitor.visitLabel(ifDoesNotMatchLabel); } switchVariableValueToField.put(totalEntries, field); totalEntries++; } if (totalEntries != keyNames.size()) { methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfKeySwitch); } } methodVisitor.visitLabel(endOfKeySwitch); Label missingField = new Label(); Label endOfFieldsSwitch = new Label(); Label[] fieldHandlerLabels = new Label[totalEntries]; for (int i = 0; i < fieldHandlerLabels.length; i++) { fieldHandlerLabels[i] = new Label(); } methodVisitor.visitVarInsn(Opcodes.ILOAD, CASE_VARIABLE); methodVisitor.visitTableSwitchInsn(0, totalEntries - 1, missingField, fieldHandlerLabels); for (int i = 0; i < totalEntries; i++) { methodVisitor.visitLabel(fieldHandlerLabels[i]); String field = switchVariableValueToField.get(i); caseWriter.accept(field); if (!doesEachCaseReturnEarly) { methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfFieldsSwitch); } } methodVisitor.visitLabel(missingField); defaultCase.run(); if (!doesEachCaseReturnEarly) { methodVisitor.visitLabel(endOfFieldsSwitch); } } public static void createIntSwitch(MethodVisitor methodVisitor, Collection<Integer> keySet, Consumer<Integer> caseWriter, Runnable defaultCase, boolean doesEachCaseReturnEarly) { if (keySet.isEmpty()) { defaultCase.run(); return; } List<Integer> sortedKeyList = keySet.stream().sorted().collect(Collectors.toList()); int[] keys = new int[sortedKeyList.size()]; Label[] keyLabels = new Label[keys.length]; { // Scoped to hide keyIndex int keyIndex = 0; for (Integer key : sortedKeyList) { keys[keyIndex] = key; keyLabels[keyIndex] = new Label(); keyIndex++; } } Label endOfKeySwitch = new Label(); Label missingKey = new Label(); methodVisitor.visitLookupSwitchInsn(missingKey, keys, keyLabels); for (int i = 0; i < keys.length; i++) { methodVisitor.visitLabel(keyLabels[i]); Integer matchingKey = sortedKeyList.get(i); caseWriter.accept(matchingKey); if (!doesEachCaseReturnEarly) { methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfKeySwitch); } } methodVisitor.visitLabel(missingKey); defaultCase.run(); if (!doesEachCaseReturnEarly) { methodVisitor.visitLabel(endOfKeySwitch); } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/CPythonBackedPythonInterpreter.java
package ai.timefold.jpyinterpreter; import java.io.InputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Function; import ai.timefold.jpyinterpreter.builtins.GlobalBuiltins; import ai.timefold.jpyinterpreter.types.CPythonBackedPythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.PythonTraceback; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.jpyinterpreter.types.wrappers.OpaquePythonReference; import ai.timefold.jpyinterpreter.types.wrappers.PythonObjectWrapper; import ai.timefold.jpyinterpreter.util.ConcurrentWeakIdentityHashMap; import ai.timefold.solver.core.api.function.PentaFunction; import ai.timefold.solver.core.api.function.QuadConsumer; import ai.timefold.solver.core.api.function.QuadFunction; import ai.timefold.solver.core.api.function.TriFunction; public class CPythonBackedPythonInterpreter implements PythonInterpreter { InputStream standardInput; PrintStream standardOutput; Scanner inputScanner; Map<ModuleSpec, PythonLikeObject> moduleSpecToModuleMap = new HashMap<>(); final Set<PythonLikeObject> hasReferenceSet = Collections.newSetFromMap(new ConcurrentWeakIdentityHashMap<>()); public static Map<Number, Object> pythonObjectIdToConvertedObjectMap = new HashMap<>(); public static Function<OpaquePythonReference, Number> lookupPythonReferenceIdPythonFunction; public static Function<OpaquePythonReference, OpaquePythonReference> lookupPythonReferenceTypePythonFunction; public static BiFunction<OpaquePythonReference, String, PythonLikeObject> lookupAttributeOnPythonReferencePythonFunction; public static BiFunction<OpaquePythonReference, String, OpaquePythonReference> lookupPointerForAttributeOnPythonReferencePythonFunction; public static BiFunction<OpaquePythonReference, String, OpaquePythonReference[]> lookupPointerArrayForAttributeOnPythonReferencePythonFunction; public static BiConsumer<Map<String, PythonLikeObject>, String> loadObjectFromPythonGlobalDict; public static TriFunction<OpaquePythonReference, String, Map<Number, PythonLikeObject>, PythonLikeObject> lookupAttributeOnPythonReferenceWithMapPythonFunction; public static QuadConsumer<OpaquePythonReference, OpaquePythonReference, String, Object> setAttributeOnPythonReferencePythonFunction; public static BiConsumer<OpaquePythonReference, String> deleteAttributeOnPythonReferencePythonFunction; public static BiFunction<OpaquePythonReference, Map<Number, PythonLikeObject>, Map<String, PythonLikeObject>> lookupDictOnPythonReferencePythonFunction; public static TriFunction<OpaquePythonReference, List<PythonLikeObject>, Map<PythonString, PythonLikeObject>, PythonLikeObject> callPythonFunction; public static PentaFunction<String, Map<String, PythonLikeObject>, Map<String, PythonLikeObject>, List<String>, Long, PythonLikeObject> importModuleFunction; public static QuadFunction<OpaquePythonReference, Map<String, PythonLikeObject>, PythonLikeTuple, PythonString, PythonObjectWrapper> createFunctionFromCodeFunction; public CPythonBackedPythonInterpreter() { this(System.in, System.out); } public CPythonBackedPythonInterpreter(InputStream standardInput, PrintStream standardOutput) { this.standardInput = standardInput; this.standardOutput = standardOutput; this.inputScanner = new Scanner(standardInput); } public static Number getPythonReferenceId(OpaquePythonReference reference) { return lookupPythonReferenceIdPythonFunction.apply(reference); } public static OpaquePythonReference getPythonReferenceType(OpaquePythonReference reference) { return lookupPythonReferenceTypePythonFunction.apply(reference); } public static PythonLikeObject lookupAttributeOnPythonReference(OpaquePythonReference object, String attribute) { return lookupAttributeOnPythonReferencePythonFunction.apply(object, attribute); } public static PythonLikeObject lookupAttributeOnPythonReference(OpaquePythonReference object, String attribute, Map<Number, PythonLikeObject> map) { return lookupAttributeOnPythonReferenceWithMapPythonFunction.apply(object, attribute, map); } public static OpaquePythonReference lookupPointerForAttributeOnPythonReference(OpaquePythonReference object, String attribute) { return lookupPointerForAttributeOnPythonReferencePythonFunction.apply(object, attribute); } public static OpaquePythonReference[] lookupPointerArrayForAttributeOnPythonReference(OpaquePythonReference object, String attribute) { return lookupPointerArrayForAttributeOnPythonReferencePythonFunction.apply(object, attribute); } public static void setAttributeOnPythonReference(OpaquePythonReference object, OpaquePythonReference cloneMap, String attribute, Object value) { setAttributeOnPythonReferencePythonFunction.accept(object, cloneMap, attribute, value); } public static void deleteAttributeOnPythonReference(OpaquePythonReference object, String attribute) { deleteAttributeOnPythonReferencePythonFunction.accept(object, attribute); } public static Map<String, PythonLikeObject> getPythonReferenceDict(OpaquePythonReference object, Map<Number, PythonLikeObject> referenceMap) { return lookupDictOnPythonReferencePythonFunction.apply(object, referenceMap); } public static void updateJavaObjectFromPythonObject(CPythonBackedPythonLikeObject javaObject, OpaquePythonReference pythonObject, Map<Number, PythonLikeObject> instanceMap) { javaObject.$setInstanceMap(instanceMap); javaObject.$setCPythonReference(pythonObject); javaObject.$readFieldsFromCPythonReference(); } public static void updateJavaObjectFromPythonObject(PythonLikeObject javaObject, OpaquePythonReference pythonObject, Map<Number, PythonLikeObject> instanceMap) { Map<String, PythonLikeObject> dict = getPythonReferenceDict(pythonObject, instanceMap); dict.forEach(javaObject::$setAttribute); } public static PythonLikeObject callPythonReference(OpaquePythonReference object, List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> keywordArguments) { return callPythonFunction.apply(object, positionalArguments, keywordArguments); } public static PythonObjectWrapper createPythonFunctionWrapper( OpaquePythonReference codeObject, Map<String, PythonLikeObject> globals, PythonLikeTuple closure, PythonString name) { return createFunctionFromCodeFunction.apply(codeObject, globals, closure, name); } @Override public boolean hasValidPythonReference(PythonLikeObject instance) { return hasReferenceSet.contains(instance); } @Override public void setPythonReference(PythonLikeObject instance, OpaquePythonReference reference) { if (instance instanceof CPythonBackedPythonLikeObject backedObject) { backedObject.$cpythonReference = reference; backedObject.$cpythonId = PythonInteger.valueOf(getPythonReferenceId(reference).longValue()); hasReferenceSet.add(backedObject); } else { throw new IllegalArgumentException( "Can only call this method on %s objects.".formatted(CPythonBackedPythonLikeObject.class.getSimpleName())); } } @Override public PythonLikeObject getGlobal(Map<String, PythonLikeObject> globalsMap, String name) { if (!globalsMap.containsKey(name)) { // This will put 'null' in the map if it doesn't exist, so we don't // do an expensive CPython lookup everytime we are getting an attribute loadObjectFromPythonGlobalDict.accept(globalsMap, name); } PythonLikeObject out = globalsMap.get(name); if (out == null) { return GlobalBuiltins.lookupOrError(this, name); } return out; } @Override public void setGlobal(Map<String, PythonLikeObject> globalsMap, String name, PythonLikeObject value) { globalsMap.put(name, value); } @Override public void deleteGlobal(Map<String, PythonLikeObject> globalsMap, String name) { globalsMap.remove(name); } @Override public PythonLikeObject importModule(PythonInteger level, List<PythonString> fromList, Map<String, PythonLikeObject> globalsMap, Map<String, PythonLikeObject> localsMap, String moduleName) { // See https://docs.python.org/3/library/functions.html#import__ for semantics ModuleSpec moduleSpec = new ModuleSpec(level, fromList, globalsMap, localsMap, moduleName); return moduleSpecToModuleMap.computeIfAbsent(moduleSpec, spec -> { Long theLevel = level.getValue().longValue(); List<String> importNameList = new ArrayList<>(fromList.size()); for (PythonString name : fromList) { importNameList.add(name.getValue()); } return importModuleFunction.apply(moduleName, globalsMap, localsMap, importNameList, theLevel); }); } @Override public void write(String output) { standardOutput.print(output); } @Override public String readLine() { // TODO: Raise EOFError on end of file return inputScanner.nextLine(); } @Override public PythonTraceback getTraceback() { // TODO: Implement this with an actually traceback return new PythonTraceback(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/CompareOp.java
package ai.timefold.jpyinterpreter; import java.util.Objects; public enum CompareOp { LESS_THAN("<", "__lt__"), LESS_THAN_OR_EQUALS("<=", "__le__"), EQUALS("==", "__eq__"), NOT_EQUALS("!=", "__ne__"), GREATER_THAN(">", "__gt__"), GREATER_THAN_OR_EQUALS(">=", "__ge__"); public final String id; public final String dunderMethod; CompareOp(String id, String dunderMethod) { this.id = id; this.dunderMethod = dunderMethod; } public static CompareOp getOpForDunderMethod(String dunderMethod) { for (CompareOp op : CompareOp.values()) { if (op.dunderMethod.equals(dunderMethod)) { return op; } } throw new IllegalArgumentException("No Op corresponds to dunder method (" + dunderMethod + ")"); } public static CompareOp getOp(String id) { for (CompareOp op : CompareOp.values()) { if (Objects.equals(op.id, id)) { return op; } } throw new IllegalArgumentException("No Op corresponds to id (" + id + ")"); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/ExceptionBlock.java
package ai.timefold.jpyinterpreter; import java.util.Objects; import java.util.Set; public class ExceptionBlock { /** * The first instruction in the try block */ final int blockStartInstructionInclusive; /** * The first instruction after the try block */ final int blockEndInstructionExclusive; /** * Where to jump to if an exception happens */ final int targetInstruction; /** * The expected stack size for this exception */ final int stackDepth; /** * If true, push the offset that the exception was raised at before pushing the exception. */ final boolean pushLastIndex; public ExceptionBlock(int blockStartInstructionInclusive, int blockEndInstructionExclusive, int targetInstruction, int stackDepth, boolean pushLastIndex) { this.blockStartInstructionInclusive = blockStartInstructionInclusive; this.blockEndInstructionExclusive = blockEndInstructionExclusive; this.targetInstruction = targetInstruction; this.stackDepth = stackDepth; this.pushLastIndex = pushLastIndex; } @Override public String toString() { StringBuilder out = new StringBuilder().append(blockStartInstructionInclusive).append(" to ") .append(blockEndInstructionExclusive) .append(" -> ").append(targetInstruction).append(" [").append(stackDepth).append("]"); if (pushLastIndex) { out.append(" lasti"); } return out.toString(); } public int getBlockStartInstructionInclusive() { return blockStartInstructionInclusive; } public int getBlockEndInstructionExclusive() { return blockEndInstructionExclusive; } public int getTargetInstruction() { return targetInstruction; } public int getStackDepth() { return stackDepth; } public boolean isPushLastIndex() { return pushLastIndex; } public boolean containsAnyTargetInSet(Set<Integer> possibleJumpTargetSet) { for (int target : possibleJumpTargetSet) { if (target <= blockStartInstructionInclusive && target < blockEndInstructionExclusive) { return true; } } return false; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ExceptionBlock that = (ExceptionBlock) o; return blockStartInstructionInclusive == that.blockStartInstructionInclusive && blockEndInstructionExclusive == that.blockEndInstructionExclusive && targetInstruction == that.targetInstruction && stackDepth == that.stackDepth && pushLastIndex == that.pushLastIndex; } @Override public int hashCode() { return Objects.hash(blockStartInstructionInclusive, blockEndInstructionExclusive, targetInstruction, stackDepth, pushLastIndex); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/FieldDescriptor.java
package ai.timefold.jpyinterpreter; import ai.timefold.jpyinterpreter.types.PythonLikeType; public record FieldDescriptor(String pythonFieldName, String javaFieldName, String declaringClassInternalName, String javaFieldTypeDescriptor, PythonLikeType fieldPythonLikeType, boolean isTrueFieldDescriptor, boolean isJavaType) { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FieldDescriptor that = (FieldDescriptor) o; return pythonFieldName.equals(that.pythonFieldName) && javaFieldName.equals(that.javaFieldName) && declaringClassInternalName.equals(that.declaringClassInternalName) && javaFieldTypeDescriptor.equals(that.javaFieldTypeDescriptor) && fieldPythonLikeType.equals(that.fieldPythonLikeType) && isTrueFieldDescriptor == that.isTrueFieldDescriptor; } @Override public String toString() { return "FieldDescriptor{" + "pythonFieldName='" + pythonFieldName + '\'' + ", javaFieldName='" + javaFieldName + '\'' + ", declaringClassInternalName='" + declaringClassInternalName + '\'' + ", javaFieldTypeDescriptor='" + javaFieldTypeDescriptor + '\'' + ", fieldPythonLikeType=" + fieldPythonLikeType + ", isTrueFieldDescriptor=" + isTrueFieldDescriptor + '}'; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/FunctionMetadata.java
package ai.timefold.jpyinterpreter; import java.util.List; import java.util.Map; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; public class FunctionMetadata { public FunctionMetadata() { } public PythonFunctionType functionType; public MethodDescriptor method; public String className; public MethodVisitor methodVisitor; public PythonCompiledFunction pythonCompiledFunction; public Map<Integer, Label> bytecodeCounterToLabelMap; public Map<Integer, List<Runnable>> bytecodeCounterToCodeArgumenterList; }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/GeneratorLocalVariableHelper.java
package ai.timefold.jpyinterpreter; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import ai.timefold.jpyinterpreter.types.PythonCell; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class GeneratorLocalVariableHelper extends LocalVariableHelper { final ClassWriter classWriter; final String classInternalName; final int cellStart; final int freeStart; int maxTemps; Map<Integer, String> slotToLocalName; Map<Integer, String> slotToLocalTypeDescriptor; public GeneratorLocalVariableHelper(ClassWriter classWriter, String classInternalName, Type[] parameters, PythonCompiledFunction compiledFunction) { super(parameters, compiledFunction); this.classWriter = classWriter; this.classInternalName = classInternalName; cellStart = compiledFunction.co_varnames.size(); freeStart = compiledFunction.co_varnames.size() + compiledFunction.co_cellvars.size(); slotToLocalName = new HashMap<>(); slotToLocalTypeDescriptor = new HashMap<>(); for (int i = 0; i < compiledFunction.co_varnames.size(); i++) { slotToLocalName.put(i, compiledFunction.co_varnames.get(i)); } for (int i = 0; i < compiledFunction.co_cellvars.size(); i++) { slotToLocalName.put(i + compiledFunction.co_varnames.size(), compiledFunction.co_cellvars.get(i)); } for (int i = 0; i < compiledFunction.co_freevars.size(); i++) { slotToLocalName.put(i + compiledFunction.co_varnames.size() + compiledFunction.co_cellvars.size(), compiledFunction.co_freevars.get(i)); } // Cannot use parameter types as the type descriptor, since the variables assigned to the // Python parameter can change types in the middle of code for (int i = 0; i < compiledFunction.co_varnames.size(); i++) { slotToLocalTypeDescriptor.put(i, Type.getDescriptor(PythonLikeObject.class)); } for (int i = 0; i < compiledFunction.co_cellvars.size(); i++) { slotToLocalTypeDescriptor.put(i + compiledFunction.co_varnames.size(), Type.getDescriptor(PythonCell.class)); } for (int i = 0; i < compiledFunction.co_freevars.size(); i++) { slotToLocalTypeDescriptor.put(i + compiledFunction.co_varnames.size() + compiledFunction.co_cellvars.size(), Type.getDescriptor(PythonCell.class)); } } GeneratorLocalVariableHelper(Type[] parameters, int argcount, int parameterSlotsEnd, int pythonCellVariablesStart, int pythonFreeVariablesStart, int pythonLocalVariablesSlotEnd, int pythonBoundVariables, int pythonFreeVariables, Map<Integer, Integer> boundCellIndexToVariableIndex, int currentExceptionVariableSlot, int callKeywordsSlot, Map<Integer, Integer> exceptionTableTargetToSavedStackMap, ClassWriter classWriter, String classInternalName, int maxTemps, int cellStart, int freeStart, Map<Integer, String> slotToLocalName, Map<Integer, String> slotToLocalTypeDescriptor) { super(parameters, argcount, parameterSlotsEnd, pythonCellVariablesStart, pythonFreeVariablesStart, pythonLocalVariablesSlotEnd, pythonBoundVariables, pythonFreeVariables, boundCellIndexToVariableIndex, currentExceptionVariableSlot, callKeywordsSlot, exceptionTableTargetToSavedStackMap); this.classWriter = classWriter; this.classInternalName = classInternalName; this.maxTemps = maxTemps; this.cellStart = cellStart; this.freeStart = freeStart; this.slotToLocalName = new HashMap<>(slotToLocalName); this.slotToLocalTypeDescriptor = new HashMap<>(slotToLocalTypeDescriptor); } public GeneratorLocalVariableHelper copy() { GeneratorLocalVariableHelper out = new GeneratorLocalVariableHelper(parameters, argcount, parameterSlotsEnd, pythonCellVariablesStart, pythonFreeVariablesStart, pythonLocalVariablesSlotEnd, pythonBoundVariables, pythonFreeVariables, boundCellIndexToVariableIndex, currentExceptionVariableSlot, callKeywordsSlot, exceptionTableTargetToSavedStackMap, classWriter, classInternalName, maxTemps, cellStart, freeStart, slotToLocalName, slotToLocalTypeDescriptor); out.usedLocals = usedLocals; return out; } private String slotToFieldName(int slot) { return "$temp" + slot; } @Override public int newLocal() { int slot = pythonLocalVariablesSlotEnd + usedLocals; usedLocals++; if (usedLocals > maxTemps) { maxTemps = usedLocals; classWriter.visitField(Modifier.PRIVATE, slotToFieldName(slot), Type.getDescriptor(Object.class), null, null); } return slot; } @Override public void freeLocal() { usedLocals--; } @Override public int getUsedLocals() { return usedLocals; } @Override public void readLocal(MethodVisitor methodVisitor, int local) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, slotToLocalName.get(local), slotToLocalTypeDescriptor.get(local)); } @Override public void writeLocal(MethodVisitor methodVisitor, int local) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, slotToLocalName.get(local), slotToLocalTypeDescriptor.get(local)); } @Override public void readCell(MethodVisitor methodVisitor, int cell) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, slotToLocalName.get(cellStart + cell), slotToLocalTypeDescriptor.get(cellStart + cell)); } @Override public void writeCell(MethodVisitor methodVisitor, int cell) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, slotToLocalName.get(cellStart + cell), slotToLocalTypeDescriptor.get(cellStart + cell)); } @Override public void writeFreeCell(MethodVisitor methodVisitor, int cell) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, slotToLocalName.get(freeStart + cell), slotToLocalTypeDescriptor.get(freeStart + cell)); } @Override public void readCurrentException(MethodVisitor methodVisitor) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, PythonGeneratorTranslator.CURRENT_EXCEPTION, Type.getDescriptor(Throwable.class)); } @Override public void writeCurrentException(MethodVisitor methodVisitor) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, PythonGeneratorTranslator.CURRENT_EXCEPTION, Type.getDescriptor(Throwable.class)); } @Override public void readExceptionTableTargetStack(MethodVisitor methodVisitor, int target) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, PythonGeneratorTranslator.exceptionHandlerTargetStackLocal(target), Type.getDescriptor(PythonLikeObject[].class)); } @Override public void writeExceptionTableTargetStack(MethodVisitor methodVisitor, int target) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, PythonGeneratorTranslator.exceptionHandlerTargetStackLocal(target), Type.getDescriptor(PythonLikeObject[].class)); } @Override public void readTemp(MethodVisitor methodVisitor, Type type, int temp) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, slotToFieldName(temp), Type.getDescriptor(Object.class)); switch (type.getSort()) { case Type.OBJECT: methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, type.getInternalName()); return; case Type.INT: { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Integer.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Integer.class), "intValue", Type.getMethodDescriptor(Type.INT_TYPE), false); } default: { throw new IllegalArgumentException("Unsupported sort: " + type.getSort()); } } } @Override public void writeTemp(MethodVisitor methodVisitor, Type type, int temp) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.SWAP); switch (type.getSort()) { case Type.OBJECT: break; case Type.INT: { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Integer.class), "valueOf", Type.getMethodDescriptor(Type.getType(Integer.class), Type.INT_TYPE), false); } default: { throw new IllegalArgumentException("Unsupported sort: " + type.getSort()); } } methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, slotToFieldName(temp), Type.getDescriptor(Object.class)); } @Override public void incrementTemp(MethodVisitor methodVisitor, int temp) { readTemp(methodVisitor, Type.INT_TYPE, temp); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.IADD); writeTemp(methodVisitor, Type.INT_TYPE, temp); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/InterfaceProxyGenerator.java
package ai.timefold.jpyinterpreter; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Set; import ai.timefold.jpyinterpreter.implementors.DelegatingInterfaceImplementor; import ai.timefold.jpyinterpreter.implementors.JavaPythonTypeConversionImplementor; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.util.MethodVisitorAdapters; import ai.timefold.jpyinterpreter.util.arguments.ArgumentSpec; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class InterfaceProxyGenerator { /** * Generate an interface that just calls an existing instance of the interface. * Needed so Java libraries that construct new instances using the no-args * constructor use the correct instance of the function (the one with __closure__ * and other instance fields). */ public static <T> Class<T> generateProxyForFunction(Class<T> interfaceClass, T interfaceInstance) { String maybeClassName = interfaceInstance.getClass().getCanonicalName() + "$Proxy"; int numberOfInstances = PythonBytecodeToJavaBytecodeTranslator.classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); var classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, internalClassName, null, Type.getInternalName(Object.class), new String[] { Type.getInternalName(interfaceClass) }); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, "proxy", Type.getDescriptor(interfaceClass), null, null); var constructor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), null, null); // Generates Proxy() {} constructor.visitCode(); constructor.visitVarInsn(Opcodes.ALOAD, 0); constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); constructor.visitInsn(Opcodes.RETURN); constructor.visitMaxs(0, 0); constructor.visitEnd(); var interfaceMethod = PythonBytecodeToJavaBytecodeTranslator.getFunctionalInterfaceMethod(interfaceClass); var interfaceMethodDescriptor = Type.getMethodDescriptor(interfaceMethod); // Generates interfaceMethod(A a, B b, ...) { return proxy.interfaceMethod(a, b, ...); } var interfaceMethodVisitor = classWriter.visitMethod(Modifier.PUBLIC, interfaceMethod.getName(), interfaceMethodDescriptor, null, null); for (var parameter : interfaceMethod.getParameters()) { interfaceMethodVisitor.visitParameter(parameter.getName(), 0); } interfaceMethodVisitor.visitCode(); interfaceMethodVisitor.visitFieldInsn(Opcodes.GETSTATIC, internalClassName, "proxy", Type.getDescriptor(interfaceClass)); for (int i = 0; i < interfaceMethod.getParameterCount(); i++) { interfaceMethodVisitor.visitVarInsn(Type.getType(interfaceMethod.getParameterTypes()[i]).getOpcode(Opcodes.ILOAD), i + 1); } interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(interfaceClass), interfaceMethod.getName(), interfaceMethodDescriptor, true); interfaceMethodVisitor.visitInsn(Type.getType(interfaceMethod.getReturnType()).getOpcode(Opcodes.IRETURN)); interfaceMethodVisitor.visitMaxs(0, 0); interfaceMethodVisitor.visitEnd(); classWriter.visitEnd(); PythonBytecodeToJavaBytecodeTranslator.writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); try { Class<T> compiledClass = (Class<T>) BuiltinTypes.asmClassLoader.loadClass(className); compiledClass.getField("proxy").set(null, interfaceInstance); return compiledClass; } catch (ClassNotFoundException e) { throw new IllegalStateException(("Impossible State: Unable to load generated class (%s)" + " despite it being just generated.").formatted(className), e); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalStateException(("Impossible State: Unable to access field on generated class (%s).") .formatted(className), e); } } /** * Generate an interface that construct a new instance of a type and delegate all calls to that type's methods. */ public static <T> Class<T> generateProxyForClass(Class<T> interfaceClass, PythonLikeType delegateType) { String maybeClassName = delegateType.getClass().getCanonicalName() + "$" + interfaceClass.getSimpleName() + "$Proxy"; int numberOfInstances = PythonBytecodeToJavaBytecodeTranslator.classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); var classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, internalClassName, null, Type.getInternalName(Object.class), new String[] { Type.getInternalName(interfaceClass) }); classWriter.visitField(Modifier.PRIVATE | Modifier.FINAL, "delegate", delegateType.getJavaTypeDescriptor(), null, null); var createdNameSet = new HashSet<String>(); for (var interfaceMethod : interfaceClass.getMethods()) { addArgumentSpecFieldForMethod(classWriter, delegateType, interfaceMethod, createdNameSet); } var constructor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), null, null); // Generates Proxy() { // delegate = new Delegate(); // } constructor.visitCode(); constructor.visitVarInsn(Opcodes.ALOAD, 0); constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); constructor.visitVarInsn(Opcodes.ALOAD, 0); constructor.visitTypeInsn(Opcodes.NEW, delegateType.getJavaTypeInternalName()); constructor.visitInsn(Opcodes.DUP); constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, delegateType.getJavaTypeInternalName(), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); constructor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, "delegate", delegateType.getJavaTypeDescriptor()); constructor.visitInsn(Opcodes.RETURN); constructor.visitMaxs(0, 0); constructor.visitEnd(); for (var interfaceMethod : interfaceClass.getMethods()) { createMethodDelegate(classWriter, internalClassName, delegateType, interfaceMethod); } classWriter.visitEnd(); PythonBytecodeToJavaBytecodeTranslator.writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); try { Class<T> compiledClass = (Class<T>) BuiltinTypes.asmClassLoader.loadClass(className); for (var interfaceMethod : interfaceClass.getMethods()) { if (!interfaceMethod.getDeclaringClass().isInterface()) { continue; } if (interfaceMethod.isDefault()) { // Default method, does not need to be present var methodType = delegateType.getMethodType(interfaceMethod.getName()); if (methodType.isEmpty()) { continue; } var function = methodType.get().getDefaultFunctionSignature(); if (function.isEmpty()) { continue; } compiledClass.getField("argumentSpec$" + interfaceMethod.getName()).set(null, function.get().getArgumentSpec()); } else { compiledClass.getField("argumentSpec$" + interfaceMethod.getName()).set(null, delegateType.getMethodType(interfaceMethod.getName()) .orElseThrow() .getDefaultFunctionSignature() .orElseThrow() .getArgumentSpec()); } } return compiledClass; } catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException e) { throw new IllegalStateException(("Impossible State: Unable to load generated class (%s)" + " despite it being just generated.").formatted(className), e); } } private static void addArgumentSpecFieldForMethod(ClassWriter classWriter, PythonLikeType delegateType, Method interfaceMethod, Set<String> createdNameSet) { if (createdNameSet.contains(interfaceMethod.getName()) || !interfaceMethod.getDeclaringClass().isInterface()) { return; } var methodType = delegateType.getMethodType(interfaceMethod.getName()); if (methodType.isEmpty()) { if (interfaceMethod.isDefault()) { return; } throw new IllegalArgumentException("Type %s cannot implement interface %s because it missing method %s." .formatted(delegateType, interfaceMethod.getDeclaringClass(), interfaceMethod)); } var function = methodType.get().getDefaultFunctionSignature(); if (function.isEmpty()) { throw new IllegalStateException(); } classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, "argumentSpec$" + interfaceMethod.getName(), Type.getDescriptor(ArgumentSpec.class), null, null); createdNameSet.add(interfaceMethod.getName()); } private static void createMethodDelegate(ClassWriter classWriter, String wrapperInternalName, PythonLikeType delegateType, Method interfaceMethod) { if (!interfaceMethod.getDeclaringClass().isInterface()) { return; } if (interfaceMethod.isDefault()) { // Default method, does not need to be present var methodType = delegateType.getMethodType(interfaceMethod.getName()); if (methodType.isEmpty()) { return; } var function = methodType.get().getDefaultFunctionSignature(); if (function.isEmpty()) { return; } } var interfaceMethodDescriptor = Type.getMethodDescriptor(interfaceMethod); // Generates interfaceMethod(A a, B b, ...) { return delegate.interfaceMethod(a, b, ...); } var interfaceMethodVisitor = classWriter.visitMethod(Modifier.PUBLIC, interfaceMethod.getName(), interfaceMethodDescriptor, null, null); interfaceMethodVisitor = MethodVisitorAdapters.adapt(interfaceMethodVisitor, interfaceMethod.getName(), interfaceMethodDescriptor); for (var parameter : interfaceMethod.getParameters()) { interfaceMethodVisitor.visitParameter(parameter.getName(), 0); } interfaceMethodVisitor.visitCode(); interfaceMethodVisitor.visitVarInsn(Opcodes.ALOAD, 0); interfaceMethodVisitor.visitFieldInsn(Opcodes.GETFIELD, wrapperInternalName, "delegate", delegateType.getJavaTypeDescriptor()); interfaceMethodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IdentityHashMap.class)); interfaceMethodVisitor.visitInsn(Opcodes.DUP); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IdentityHashMap.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); interfaceMethodVisitor.visitVarInsn(Opcodes.ASTORE, interfaceMethod.getParameterCount() + 1); interfaceMethodVisitor.visitFieldInsn(Opcodes.GETSTATIC, wrapperInternalName, "argumentSpec$" + interfaceMethod.getName(), Type.getDescriptor(ArgumentSpec.class)); var functionSignature = delegateType.getMethodType(interfaceMethod.getName()) .orElseThrow(() -> new IllegalArgumentException( "Type %s cannot implement interface %s because it missing method %s." .formatted(delegateType, interfaceMethod.getDeclaringClass(), interfaceMethod))) .getDefaultFunctionSignature() .orElseThrow(); DelegatingInterfaceImplementor.prepareParametersForMethodCallFromArgumentSpec( interfaceMethod, interfaceMethodVisitor, functionSignature.getParameterTypes().length, Type.getType(functionSignature.getMethodDescriptor().getMethodDescriptor()), false); functionSignature.getMethodDescriptor().callMethod(interfaceMethodVisitor); var returnType = interfaceMethod.getReturnType(); if (returnType.equals(void.class)) { interfaceMethodVisitor.visitInsn(Opcodes.RETURN); } else { if (returnType.isPrimitive()) { JavaPythonTypeConversionImplementor.loadTypeClass(returnType, interfaceMethodVisitor); } else { interfaceMethodVisitor.visitLdcInsn(Type.getType(returnType)); } interfaceMethodVisitor.visitInsn(Opcodes.SWAP); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "convertPythonObjectToJavaType", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Class.class), Type.getType( PythonLikeObject.class)), false); if (returnType.isPrimitive()) { JavaPythonTypeConversionImplementor.unboxBoxedPrimitiveType(returnType, interfaceMethodVisitor); interfaceMethodVisitor.visitInsn(Type.getType(returnType).getOpcode(Opcodes.IRETURN)); } else { interfaceMethodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(returnType)); interfaceMethodVisitor.visitInsn(Opcodes.ARETURN); } } interfaceMethodVisitor.visitMaxs(interfaceMethod.getParameterCount() + 2, 1); interfaceMethodVisitor.visitEnd(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/InterpreterStartupOptions.java
package ai.timefold.jpyinterpreter; import java.nio.file.Path; /** * A class that holds startup options for the interpreter that are used when the JVM starts */ public final class InterpreterStartupOptions { /** * Where to output class files; defaults to null (which cause not class files to not be written) */ public static Path classOutputRootPath = null; }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/LocalVariableHelper.java
package ai.timefold.jpyinterpreter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class LocalVariableHelper { public final Type[] parameters; public final int argcount; public final int parameterSlotsEnd; public final int pythonCellVariablesStart; public final int pythonFreeVariablesStart; public final int pythonLocalVariablesSlotEnd; public final int pythonBoundVariables; public final int pythonFreeVariables; public final Map<Integer, Integer> boundCellIndexToVariableIndex; public final int currentExceptionVariableSlot; public final int callKeywordsSlot; public final Map<Integer, Integer> exceptionTableTargetToSavedStackMap; int usedLocals; public LocalVariableHelper(Type[] parameters, PythonCompiledFunction compiledFunction) { this.argcount = compiledFunction.totalArgCount(); this.parameters = parameters; int slotsUsedByParameters = 1; for (Type parameter : parameters) { if (parameter.equals(Type.LONG_TYPE) || parameter.equals(Type.DOUBLE_TYPE)) { slotsUsedByParameters += 2; } else { slotsUsedByParameters += 1; } } pythonBoundVariables = compiledFunction.co_cellvars.size(); pythonFreeVariables = compiledFunction.co_freevars.size(); parameterSlotsEnd = slotsUsedByParameters; pythonCellVariablesStart = parameterSlotsEnd + compiledFunction.co_varnames.size(); pythonFreeVariablesStart = pythonCellVariablesStart + pythonBoundVariables; currentExceptionVariableSlot = pythonFreeVariablesStart + pythonFreeVariables; callKeywordsSlot = currentExceptionVariableSlot + 1; exceptionTableTargetToSavedStackMap = new HashMap<>(); for (int target : compiledFunction.co_exceptiontable.getJumpTargetSet()) { exceptionTableTargetToSavedStackMap.put(target, callKeywordsSlot + 1 + exceptionTableTargetToSavedStackMap.size()); } pythonLocalVariablesSlotEnd = callKeywordsSlot + 1 + exceptionTableTargetToSavedStackMap.size(); boundCellIndexToVariableIndex = new HashMap<>(); for (int i = 0; i < compiledFunction.co_cellvars.size(); i++) { for (int j = 0; j < compiledFunction.co_varnames.size(); j++) { if (compiledFunction.co_cellvars.get(i).equals(compiledFunction.co_varnames.get(j))) { boundCellIndexToVariableIndex.put(i, j); break; } } if (!boundCellIndexToVariableIndex.containsKey(i)) { boundCellIndexToVariableIndex.put(i, pythonCellVariablesStart + i); } } } LocalVariableHelper(Type[] parameters, int argcount, int parameterSlotsEnd, int pythonCellVariablesStart, int pythonFreeVariablesStart, int pythonLocalVariablesSlotEnd, int pythonBoundVariables, int pythonFreeVariables, Map<Integer, Integer> boundCellIndexToVariableIndex, int currentExceptionVariableSlot, int callKeywordsSlot, Map<Integer, Integer> exceptionTableTargetToSavedStackMap) { this.argcount = argcount; this.parameters = parameters; this.parameterSlotsEnd = parameterSlotsEnd; this.pythonCellVariablesStart = pythonCellVariablesStart; this.pythonFreeVariablesStart = pythonFreeVariablesStart; this.pythonLocalVariablesSlotEnd = pythonLocalVariablesSlotEnd; this.pythonBoundVariables = pythonBoundVariables; this.pythonFreeVariables = pythonFreeVariables; this.boundCellIndexToVariableIndex = boundCellIndexToVariableIndex; this.currentExceptionVariableSlot = currentExceptionVariableSlot; this.callKeywordsSlot = callKeywordsSlot; this.exceptionTableTargetToSavedStackMap = exceptionTableTargetToSavedStackMap; } public LocalVariableHelper copy() { LocalVariableHelper out = new LocalVariableHelper(parameters, argcount, parameterSlotsEnd, pythonCellVariablesStart, pythonFreeVariablesStart, pythonLocalVariablesSlotEnd, pythonBoundVariables, pythonFreeVariables, boundCellIndexToVariableIndex, currentExceptionVariableSlot, callKeywordsSlot, exceptionTableTargetToSavedStackMap); out.usedLocals = usedLocals; return out; } public int getParameterSlot(int parameterIndex) { if (parameterIndex > parameters.length) { throw new IndexOutOfBoundsException("Asked for the slot corresponding to the (" + parameterIndex + ") " + "parameter, but there are only (" + parameters.length + ") parameters (" + Arrays.toString(parameters) + ")."); } int slotsUsedByParameters = 1; for (int i = 0; i < parameterIndex; i++) { if (parameters[i].equals(Type.LONG_TYPE) || parameters[i].equals(Type.DOUBLE_TYPE)) { slotsUsedByParameters += 2; } else { slotsUsedByParameters += 1; } } return slotsUsedByParameters; } public int getPythonLocalVariableSlot(int index) { return parameterSlotsEnd + index; } public int getPythonCellOrFreeVariableSlot(int index) { return pythonCellVariablesStart + index; } public int getCurrentExceptionVariableSlot() { return currentExceptionVariableSlot; } public int getCallKeywordsSlot() { return callKeywordsSlot; } public int getNumberOfFreeCells() { return pythonFreeVariables; } public int getNumberOfBoundCells() { return pythonBoundVariables; } public int getNumberOfCells() { return pythonBoundVariables + pythonFreeVariables; } public int getNumberOfLocalVariables() { return pythonCellVariablesStart - parameterSlotsEnd; } public int newLocal() { int slot = pythonLocalVariablesSlotEnd + usedLocals; usedLocals++; return slot; } public void freeLocal() { usedLocals--; } public int getUsedLocals() { return usedLocals; } public void readLocal(MethodVisitor methodVisitor, int local) { methodVisitor.visitVarInsn(Opcodes.ALOAD, getPythonLocalVariableSlot(local)); } public void writeLocal(MethodVisitor methodVisitor, int local) { methodVisitor.visitVarInsn(Opcodes.ASTORE, getPythonLocalVariableSlot(local)); } public void readCellInitialValue(MethodVisitor methodVisitor, int cell) { if (boundCellIndexToVariableIndex.containsKey(cell)) { int boundedVariable = boundCellIndexToVariableIndex.get(cell); if (boundedVariable >= argcount) { // not a parameter methodVisitor.visitInsn(Opcodes.ACONST_NULL); } else { // it is a parameter readLocal(methodVisitor, boundCellIndexToVariableIndex.get(cell)); } } else { throw new IllegalStateException("Cannot find corresponding slot for bounded cell " + cell + " in map " + boundCellIndexToVariableIndex); } } public void readCell(MethodVisitor methodVisitor, int cell) { methodVisitor.visitVarInsn(Opcodes.ALOAD, getPythonCellOrFreeVariableSlot(cell)); } public void writeCell(MethodVisitor methodVisitor, int cell) { methodVisitor.visitVarInsn(Opcodes.ASTORE, getPythonCellOrFreeVariableSlot(cell)); } public void writeFreeCell(MethodVisitor methodVisitor, int cell) { methodVisitor.visitVarInsn(Opcodes.ASTORE, pythonFreeVariablesStart + cell); } public void readCurrentException(MethodVisitor methodVisitor) { methodVisitor.visitVarInsn(Opcodes.ALOAD, getCurrentExceptionVariableSlot()); } public void writeCurrentException(MethodVisitor methodVisitor) { methodVisitor.visitVarInsn(Opcodes.ASTORE, getCurrentExceptionVariableSlot()); } public int getExceptionTableTargetStackSlot(int target) { return exceptionTableTargetToSavedStackMap.get(target); } public void readExceptionTableTargetStack(MethodVisitor methodVisitor, int target) { methodVisitor.visitVarInsn(Opcodes.ALOAD, getExceptionTableTargetStackSlot(target)); } public void writeExceptionTableTargetStack(MethodVisitor methodVisitor, int target) { methodVisitor.visitVarInsn(Opcodes.ASTORE, getExceptionTableTargetStackSlot(target)); } public void setupInitialStoredExceptionStacks(MethodVisitor methodVisitor) { for (Integer target : exceptionTableTargetToSavedStackMap.keySet()) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); writeExceptionTableTargetStack(methodVisitor, target); } } public void readCallKeywords(MethodVisitor methodVisitor) { methodVisitor.visitVarInsn(Opcodes.ALOAD, getCallKeywordsSlot()); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeTuple.class)); } public void writeCallKeywords(MethodVisitor methodVisitor) { methodVisitor.visitVarInsn(Opcodes.ASTORE, getCallKeywordsSlot()); } public void resetCallKeywords(MethodVisitor methodVisitor) { methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(PythonLikeTuple.class), "EMPTY", Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitVarInsn(Opcodes.ASTORE, getCallKeywordsSlot()); } public void readTemp(MethodVisitor methodVisitor, Type type, int temp) { methodVisitor.visitVarInsn(type.getOpcode(Opcodes.ILOAD), temp); } public void writeTemp(MethodVisitor methodVisitor, Type type, int temp) { methodVisitor.visitVarInsn(type.getOpcode(Opcodes.ISTORE), temp); } public void incrementTemp(MethodVisitor methodVisitor, int temp) { methodVisitor.visitIincInsn(temp, 1); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/MethodDescriptor.java
package ai.timefold.jpyinterpreter; import java.lang.reflect.Constructor; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class MethodDescriptor { private final String declaringClassInternalName; private final String methodName; private final String methodDescriptor; private final MethodType methodType; private static Type resolveGenericType(java.lang.reflect.Type type, TypeVariable[] interfaceTypeVariables, List<Class<?>> typeArgumentList) { if (type instanceof Class) { return Type.getType((Class<?>) type); } else if (type instanceof TypeVariable) { for (int i = 0; i < interfaceTypeVariables.length; i++) { if (interfaceTypeVariables[i].equals(type)) { return Type.getType(typeArgumentList.get(i)); } } throw new IllegalStateException("Unknown TypeVariable " + type); } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; java.lang.reflect.Type[] lowerBounds = wildcardType.getLowerBounds(); java.lang.reflect.Type[] upperBounds = wildcardType.getUpperBounds(); if (lowerBounds.length > 0) { return resolveGenericType(lowerBounds[0], interfaceTypeVariables, typeArgumentList); } if (upperBounds.length > 0) { return resolveGenericType(upperBounds[0], interfaceTypeVariables, typeArgumentList); } throw new IllegalStateException("Wildcard Type " + wildcardType + " has no upper or lower bounds."); } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; return resolveGenericType(parameterizedType.getRawType(), interfaceTypeVariables, typeArgumentList); } else if (type instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) type; return Type.getType('[' + resolveGenericType(genericArrayType.getGenericComponentType(), interfaceTypeVariables, typeArgumentList).getDescriptor()); } else { throw new IllegalArgumentException("Unknown class (" + type.getClass() + ") of argument (" + type + ")"); } } public MethodDescriptor(Class<?> interfaceClass, Method method, List<Class<?>> typeArgumentList) { TypeVariable[] interfaceTypeVariables = interfaceClass.getTypeParameters(); if (interfaceTypeVariables.length != typeArgumentList.size()) { throw new IllegalArgumentException("Type argument list (" + typeArgumentList + ") does not have same size as " + interfaceClass + " generic argument list (" + Arrays.toString(interfaceTypeVariables) + ")"); } this.declaringClassInternalName = Type.getInternalName(method.getDeclaringClass()); this.methodName = method.getName(); if (method.getDeclaringClass().isInterface()) { this.methodType = MethodType.INTERFACE; } else if (Modifier.isStatic(method.getModifiers())) { this.methodType = MethodType.STATIC; } else { this.methodType = MethodType.VIRTUAL; } String methodDescriptorString = ""; Type returnType = resolveGenericType(method.getGenericReturnType(), interfaceTypeVariables, typeArgumentList); Type[] argumentTypes = new Type[method.getParameterCount()]; for (int i = 0; i < argumentTypes.length; i++) { argumentTypes[i] = resolveGenericType(method.getGenericParameterTypes()[i], interfaceTypeVariables, typeArgumentList); } this.methodDescriptor = Type.getMethodDescriptor(returnType, argumentTypes); } public MethodDescriptor(Method method) { this.declaringClassInternalName = Type.getInternalName(method.getDeclaringClass()); this.methodName = method.getName(); this.methodDescriptor = Type.getMethodDescriptor(method); if (method.getDeclaringClass().isInterface()) { this.methodType = MethodType.INTERFACE; } else if (Modifier.isStatic(method.getModifiers())) { this.methodType = MethodType.STATIC; } else { this.methodType = MethodType.VIRTUAL; } } public MethodDescriptor(Method method, MethodType type) { this.declaringClassInternalName = Type.getInternalName(method.getDeclaringClass()); this.methodName = method.getName(); this.methodDescriptor = Type.getMethodDescriptor(method); this.methodType = type; } public MethodDescriptor(Constructor<?> constructor) { this.declaringClassInternalName = Type.getInternalName(constructor.getDeclaringClass()); this.methodName = constructor.getName(); this.methodDescriptor = Type.getConstructorDescriptor(constructor); this.methodType = MethodType.CONSTRUCTOR; } public MethodDescriptor(String declaringClassInternalName, MethodType methodType, String methodName, String methodDescriptor) { this.declaringClassInternalName = declaringClassInternalName; this.methodName = methodName; this.methodDescriptor = methodDescriptor; this.methodType = methodType; } public MethodDescriptor(Class<?> declaringClass, MethodType methodType, String methodName, Class<?> returnType, Class<?>... parameterTypes) { this.declaringClassInternalName = Type.getInternalName(declaringClass); this.methodName = methodName; Type[] parameterAsmTypes = new Type[parameterTypes.length]; for (int i = 0; i < parameterAsmTypes.length; i++) { parameterAsmTypes[i] = Type.getType(parameterTypes[i]); } this.methodDescriptor = Type.getMethodDescriptor(Type.getType(returnType), parameterAsmTypes); this.methodType = methodType; } public static MethodDescriptor useStaticMethodAsVirtual(Method method) { return new MethodDescriptor(method.getDeclaringClass(), MethodType.STATIC_AS_VIRTUAL, method.getName(), method.getReturnType(), method.getParameterTypes()); } public String getDeclaringClassInternalName() { return declaringClassInternalName; } public String getMethodName() { return methodName; } public String getMethodDescriptor() { return methodDescriptor; } public MethodType getMethodType() { return methodType; } public void callMethod(MethodVisitor methodVisitor) { methodVisitor.visitMethodInsn(getMethodType().getOpcode(), getDeclaringClassInternalName(), getMethodName(), getMethodDescriptor(), getMethodType() == MethodType.INTERFACE); } public MethodDescriptor withReturnType(Type returnType) { return new MethodDescriptor(getDeclaringClassInternalName(), getMethodType(), getMethodName(), Type.getMethodDescriptor(returnType, Type.getArgumentTypes(getMethodDescriptor()))); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MethodDescriptor that = (MethodDescriptor) o; return getDeclaringClassInternalName().equals(that.getDeclaringClassInternalName()) && getMethodName().equals(that.getMethodName()) && getMethodDescriptor().equals(that.getMethodDescriptor()); } @Override public int hashCode() { return Objects.hash(getDeclaringClassInternalName(), getMethodName(), getMethodDescriptor()); } public Type getReturnType() { return Type.getReturnType(getMethodDescriptor()); } public Type[] getParameterTypes() { return Type.getArgumentTypes(getMethodDescriptor()); } public enum MethodType { VIRTUAL(Opcodes.INVOKEVIRTUAL, false), STATIC(Opcodes.INVOKESTATIC, true), CLASS(Opcodes.INVOKESTATIC, true), STATIC_AS_VIRTUAL(Opcodes.INVOKESTATIC, true), INTERFACE(Opcodes.INVOKEINTERFACE, false), CONSTRUCTOR(Opcodes.INVOKESPECIAL, false); private final int opcode; private final boolean isStatic; MethodType(int opcode, boolean isStatic) { this.opcode = opcode; this.isStatic = isStatic; } public int getOpcode() { return opcode; } public boolean isStatic() { return isStatic; } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/ModuleSpec.java
package ai.timefold.jpyinterpreter; import java.util.List; import java.util.Map; import java.util.Objects; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; public final class ModuleSpec { final PythonInteger level; final List<PythonString> fromList; final Map<String, PythonLikeObject> globalsMap; final Map<String, PythonLikeObject> localsMap; final String name; public ModuleSpec(PythonInteger level, List<PythonString> fromList, Map<String, PythonLikeObject> globalsMap, Map<String, PythonLikeObject> localsMap, String name) { this.level = level; this.fromList = fromList; this.globalsMap = globalsMap; this.localsMap = localsMap; this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ModuleSpec that = (ModuleSpec) o; return level.equals(that.level) && fromList.equals(that.fromList) && globalsMap == that.globalsMap && localsMap == that.localsMap && name.equals(that.name); } @Override public int hashCode() { return Objects.hash(level, fromList, System.identityHashCode(globalsMap), System.identityHashCode(localsMap), name); } @Override public String toString() { return "ModuleSpec{" + "name='" + name + '\'' + ", level=" + level + ", fromList=" + fromList + ", globalsMap=" + System.identityHashCode(globalsMap) + ", localsMap=" + System.identityHashCode(localsMap) + '}'; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonBinaryOperator.java
package ai.timefold.jpyinterpreter; import java.util.Optional; import ai.timefold.jpyinterpreter.opcodes.dunder.BinaryDunderOpcode; /** * The list of all Python Binary Operators, which are performed * by calling the left operand's corresponding dunder method on the * right operand * * ex: a.__add__(b) */ public enum PythonBinaryOperator { // Comparable operations ( from https://docs.python.org/3/reference/datamodel.html#object.__lt__ ) LESS_THAN("<", "__lt__", "__gt__", true), LESS_THAN_OR_EQUAL("<=", "__le__", "__ge__", true), GREATER_THAN(">", "__gt__", "__lt__", true), GREATER_THAN_OR_EQUAL(">=", "__ge__", "__le__", true), EQUAL("==", "__eq__", "__eq__", true), NOT_EQUAL("!=", "__ne__", "__ne__", true), // Numeric binary operations ( from https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types ) POWER("**", "__pow__", "__rpow__"), MULTIPLY("*", "__mul__", "__rmul__"), MATRIX_MULTIPLY("@", "__matmul__", "__rmatmul__"), FLOOR_DIVIDE("//", "__floordiv__", "__rfloordiv__"), TRUE_DIVIDE("/", "__truediv__", "__rtruediv__"), MODULO("%", "__mod__", "__rmod__"), ADD("+", "__add__", "__radd__"), SUBTRACT("-", "__sub__", "__rsub__"), LSHIFT("<<", "__lshift__", "__rlshift__"), RSHIFT(">>", "__rshift__", "__rrshift__"), AND("&", "__and__", "__rand__"), XOR("^", "__xor__", "__rxor__"), OR("|", "__or__", "__ror__"), // In-place numeric binary operations variations INPLACE_POWER("**=", "__ipow__", PythonBinaryOperator.POWER), INPLACE_MULTIPLY("*=", "__imul__", PythonBinaryOperator.MULTIPLY), INPLACE_MATRIX_MULTIPLY("@=", "__imatmul__", PythonBinaryOperator.MATRIX_MULTIPLY), INPLACE_FLOOR_DIVIDE("//=", "__ifloordiv__", PythonBinaryOperator.FLOOR_DIVIDE), INPLACE_TRUE_DIVIDE("/=", "__itruediv__", PythonBinaryOperator.TRUE_DIVIDE), INPLACE_MODULO("%=", "__imod__", PythonBinaryOperator.MODULO), INPLACE_ADD("+=", "__iadd__", PythonBinaryOperator.ADD), INPLACE_SUBTRACT("-=", "__isub__", PythonBinaryOperator.SUBTRACT), INPLACE_LSHIFT("<<=", "__ilshift__", PythonBinaryOperator.LSHIFT), INPLACE_RSHIFT(">>=", "__irshift__", PythonBinaryOperator.RSHIFT), INPLACE_AND("&=", "__iand__", PythonBinaryOperator.AND), INPLACE_XOR("^=", "__ixor__", PythonBinaryOperator.XOR), INPLACE_OR("|=", "__ior__", PythonBinaryOperator.OR), // List operations // https://docs.python.org/3/reference/datamodel.html#object.__getitem__ GET_ITEM("", "__getitem__"), DELETE_ITEM("", "__delitem__"), // Generator operations // https://docs.python.org/3/reference/expressions.html#generator-iterator-methods SEND("", "send"), THROW("", "throw"), // Membership operations // https://docs.python.org/3/reference/expressions.html#membership-test-operations CONTAINS("", "__contains__"), // Descriptor operations // https://docs.python.org/3/howto/descriptor.html DELETE("", "__delete__"), // Attribute access GET_ATTRIBUTE("", "__getattribute__"), GET_ATTRIBUTE_NOT_IN_SLOTS("", "__getattr__"), DELETE_ATTRIBUTE("", "__delattr__"), // Format string: https://peps.python.org/pep-3101/ FORMAT("", "__format__"), // global builtins DIVMOD("", "__divmod__"); public final String operatorSymbol; public final String dunderMethod; public final String rightDunderMethod; public final boolean isComparisonMethod; public final PythonBinaryOperator fallbackOperation; PythonBinaryOperator(String operatorSymbol, String dunderMethod) { this.operatorSymbol = operatorSymbol; this.dunderMethod = dunderMethod; this.rightDunderMethod = null; this.isComparisonMethod = false; this.fallbackOperation = null; } PythonBinaryOperator(String operatorSymbol, String dunderMethod, String rightDunderMethod) { this.operatorSymbol = operatorSymbol; this.dunderMethod = dunderMethod; this.rightDunderMethod = rightDunderMethod; this.isComparisonMethod = false; this.fallbackOperation = null; } PythonBinaryOperator(String operatorSymbol, String dunderMethod, String rightDunderMethod, boolean isComparisonMethod) { this.operatorSymbol = operatorSymbol; this.dunderMethod = dunderMethod; this.rightDunderMethod = rightDunderMethod; this.isComparisonMethod = isComparisonMethod; this.fallbackOperation = null; } PythonBinaryOperator(String operatorSymbol, String dunderMethod, PythonBinaryOperator fallbackOperation) { this.operatorSymbol = operatorSymbol; this.dunderMethod = dunderMethod; this.rightDunderMethod = null; this.isComparisonMethod = false; this.fallbackOperation = fallbackOperation; } public String getOperatorSymbol() { return operatorSymbol; } public String getDunderMethod() { return dunderMethod; } public String getRightDunderMethod() { return rightDunderMethod; } public boolean hasRightDunderMethod() { return rightDunderMethod != null; } public boolean isComparisonMethod() { return isComparisonMethod; } public Optional<PythonBinaryOperator> getFallbackOperation() { return Optional.ofNullable(fallbackOperation); } public static BinaryDunderOpcode getBinaryOpcode(PythonBytecodeInstruction instruction) { // As defined by https://github.com/python/cpython/blob/0faa0ba240e815614e5a2900e48007acac41b214/Python/ceval.c#L299 // Binary operations are in alphabetical order (note: CPython refer to Modulo as Remainder), // and are followed by the inplace operations in the same order return new BinaryDunderOpcode(instruction, switch (instruction.arg()) { case 0 -> PythonBinaryOperator.ADD; case 1 -> PythonBinaryOperator.AND; case 2 -> PythonBinaryOperator.FLOOR_DIVIDE; case 3 -> PythonBinaryOperator.LSHIFT; case 4 -> PythonBinaryOperator.MATRIX_MULTIPLY; case 5 -> PythonBinaryOperator.MULTIPLY; case 6 -> PythonBinaryOperator.MODULO; case 7 -> PythonBinaryOperator.OR; case 8 -> PythonBinaryOperator.POWER; case 9 -> PythonBinaryOperator.RSHIFT; case 10 -> PythonBinaryOperator.SUBTRACT; case 11 -> PythonBinaryOperator.TRUE_DIVIDE; case 12 -> PythonBinaryOperator.XOR; case 13 -> PythonBinaryOperator.INPLACE_ADD; case 14 -> PythonBinaryOperator.INPLACE_AND; case 15 -> PythonBinaryOperator.INPLACE_FLOOR_DIVIDE; case 16 -> PythonBinaryOperator.INPLACE_LSHIFT; case 17 -> PythonBinaryOperator.INPLACE_MATRIX_MULTIPLY; case 18 -> PythonBinaryOperator.INPLACE_MULTIPLY; case 19 -> PythonBinaryOperator.INPLACE_MODULO; case 20 -> PythonBinaryOperator.INPLACE_OR; case 21 -> PythonBinaryOperator.INPLACE_POWER; case 22 -> PythonBinaryOperator.INPLACE_RSHIFT; case 23 -> PythonBinaryOperator.INPLACE_SUBTRACT; case 24 -> PythonBinaryOperator.INPLACE_TRUE_DIVIDE; case 25 -> PythonBinaryOperator.INPLACE_XOR; default -> throw new IllegalArgumentException("Unknown binary op id: " + instruction.arg()); }); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonBuiltinOperations.java
package ai.timefold.jpyinterpreter; public class PythonBuiltinOperations { }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonBytecodeInstruction.java
package ai.timefold.jpyinterpreter; import java.util.OptionalInt; import ai.timefold.jpyinterpreter.opcodes.descriptor.OpcodeDescriptor; public record PythonBytecodeInstruction(String opname, int offset, int arg, String argRepr, OptionalInt startsLine, boolean isJumpTarget) { public static PythonBytecodeInstruction atOffset(String opname, int offset) { return new PythonBytecodeInstruction(opname, offset, 0, "", OptionalInt.empty(), false); } public static PythonBytecodeInstruction atOffset(OpcodeDescriptor instruction, int offset) { return atOffset(instruction.name(), offset); } public PythonBytecodeInstruction withArg(int newArg) { return new PythonBytecodeInstruction(opname, offset, newArg, argRepr, startsLine, isJumpTarget); } public PythonBytecodeInstruction withArgRepr(String newArgRepr) { return new PythonBytecodeInstruction(opname, offset, arg, newArgRepr, startsLine, isJumpTarget); } public PythonBytecodeInstruction startsLine(int lineNumber) { return new PythonBytecodeInstruction(opname, offset, arg, argRepr, OptionalInt.of(lineNumber), isJumpTarget); } public PythonBytecodeInstruction withIsJumpTarget(boolean isJumpTarget) { return new PythonBytecodeInstruction(opname, offset, arg, argRepr, startsLine, isJumpTarget); } public PythonBytecodeInstruction markAsJumpTarget() { return new PythonBytecodeInstruction(opname, offset, arg, argRepr, startsLine, true); } @Override public String toString() { return "[%d] %s (%d) %s" .formatted(offset, opname, arg, isJumpTarget ? "{JUMP TARGET}" : ""); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonBytecodeToJavaBytecodeTranslator.java
package ai.timefold.jpyinterpreter; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; 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.TreeSet; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import ai.timefold.jpyinterpreter.dag.FlowGraph; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.implementors.FunctionImplementor; import ai.timefold.jpyinterpreter.implementors.JavaPythonTypeConversionImplementor; import ai.timefold.jpyinterpreter.implementors.StackManipulationImplementor; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.OpcodeWithoutSource; import ai.timefold.jpyinterpreter.opcodes.SelfOpcodeWithoutSource; import ai.timefold.jpyinterpreter.opcodes.descriptor.GeneratorOpDescriptor; import ai.timefold.jpyinterpreter.opcodes.variable.LoadFastAndClearOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; import ai.timefold.jpyinterpreter.types.wrappers.OpaquePythonReference; import ai.timefold.jpyinterpreter.types.wrappers.PythonObjectWrapper; import ai.timefold.jpyinterpreter.util.JavaPythonClassWriter; import ai.timefold.jpyinterpreter.util.MethodVisitorAdapters; import ai.timefold.jpyinterpreter.util.arguments.ArgumentSpec; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PythonBytecodeToJavaBytecodeTranslator { public static final String USER_PACKAGE_BASE = "org.jpyinterpreter.user."; public static final String GENERATED_PACKAGE_BASE = "org.jpyinterpreter.synthetic."; public static final String CONSTANTS_STATIC_FIELD_NAME = "co_consts"; public static final String NAMES_STATIC_FIELD_NAME = "co_names"; public static final String VARIABLE_NAMES_STATIC_FIELD_NAME = "co_varnames"; public static final String GLOBALS_MAP_STATIC_FIELD_NAME = "__globals__"; public static final String CLASS_CELL_STATIC_FIELD_NAME = "__class_cell__"; public static final String ARGUMENT_SPEC_GETTER_STATIC_FIELD_NAME = "__spec_getter__"; public static final String PYTHON_WRAPPER_CODE_STATIC_FIELD_NAME = "__code__"; public static final String DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME = "__defaults__"; public static final String DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME = "__kwdefaults__"; public static final String ANNOTATION_DIRECTORY_INSTANCE_FIELD_NAME = "__annotations__"; public static final String CELLS_INSTANCE_FIELD_NAME = "__closure__"; public static final String QUALIFIED_NAME_INSTANCE_FIELD_NAME = "__qualname__"; public static final String ARGUMENT_SPEC_INSTANCE_FIELD_NAME = "__spec__"; public static final String INTERPRETER_INSTANCE_FIELD_NAME = "__interpreter__"; public static final String PYTHON_WRAPPER_FUNCTION_INSTANCE_FIELD_NAME = "__function__"; public static final Map<String, Integer> classNameToSharedInstanceCount = new HashMap<>(); private static final Logger LOGGER = LoggerFactory.getLogger(PythonBytecodeToJavaBytecodeTranslator.class); public static Path classOutputRootPath = InterpreterStartupOptions.classOutputRootPath; static { BuiltinTypes.load(); } public static void writeClassOutput(Map<String, byte[]> classNameToBytecode, String className, byte[] classByteCode) { classNameToBytecode.put(className, classByteCode); if (classOutputRootPath == null) { return; } String[] parts = (className.replace('.', '/') + ".class").split("/"); Path classFileLocation = classOutputRootPath.resolve(Path.of(".", parts)); try { Files.createDirectories(classFileLocation.getParent()); Files.write(classFileLocation, classByteCode); } catch (IOException e) { throw new RuntimeException(e); } } public static Method getFunctionalInterfaceMethod(Class<?> interfaceClass) { List<Method> candidateList = new ArrayList<>(); for (Method method : interfaceClass.getMethods()) { if (Modifier.isAbstract(method.getModifiers())) { candidateList.add(method); } } if (candidateList.isEmpty()) { throw new IllegalArgumentException("Class (" + interfaceClass.getName() + ") is not a functional interface: " + "it has no abstract methods."); } if (candidateList.size() > 1) { throw new IllegalArgumentException("Class (" + interfaceClass.getName() + ") is not a functional interface: " + "it has multiple abstract methods (" + candidateList + ")."); } return candidateList.get(0); } public static <T> T createInstance(Class<T> functionClass, PythonInterpreter pythonInterpreter) { return FunctionImplementor.createInstance(new PythonLikeTuple(), new PythonLikeDict(), new PythonLikeTuple(), new PythonLikeTuple(), PythonString.valueOf(functionClass.getName()), functionClass, pythonInterpreter); } public static <T> T translatePythonBytecode(PythonCompiledFunction pythonCompiledFunction, Class<T> javaFunctionalInterfaceType) { Class<T> compiledClass = translatePythonBytecodeToClass(pythonCompiledFunction, javaFunctionalInterfaceType); PythonLikeTuple annotationTuple = pythonCompiledFunction.typeAnnotations.entrySet() .stream() .map(entry -> PythonLikeTuple.fromItems(PythonString.valueOf(entry.getKey()), entry.getValue() != null ? entry.getValue().type() : BuiltinTypes.BASE_TYPE)) .collect(Collectors.toCollection(PythonLikeTuple::new)); return FunctionImplementor.createInstance(pythonCompiledFunction.defaultPositionalArguments, pythonCompiledFunction.defaultKeywordArguments, annotationTuple, pythonCompiledFunction.closure, PythonString.valueOf(compiledClass.getName()), compiledClass, PythonInterpreter.DEFAULT); } public static <T> T translatePythonBytecode(PythonCompiledFunction pythonCompiledFunction, Class<T> javaFunctionalInterfaceType, List<Class<?>> genericTypeArgumentList) { Class<T> compiledClass = translatePythonBytecodeToClass(pythonCompiledFunction, javaFunctionalInterfaceType, genericTypeArgumentList); PythonLikeTuple annotationTuple = pythonCompiledFunction.typeAnnotations.entrySet() .stream() .map(entry -> PythonLikeTuple.fromItems(PythonString.valueOf(entry.getKey()), entry.getValue().type())) .collect(Collectors.toCollection(PythonLikeTuple::new)); return FunctionImplementor.createInstance(pythonCompiledFunction.defaultPositionalArguments, pythonCompiledFunction.defaultKeywordArguments, annotationTuple, pythonCompiledFunction.closure, PythonString.valueOf(compiledClass.getName()), compiledClass, PythonInterpreter.DEFAULT); } public static <T> T forceTranslatePythonBytecodeToGenerator(PythonCompiledFunction pythonCompiledFunction, Class<T> javaFunctionalInterfaceType) { Method methodWithoutGenerics = getFunctionalInterfaceMethod(javaFunctionalInterfaceType); MethodDescriptor methodDescriptor = new MethodDescriptor(javaFunctionalInterfaceType, methodWithoutGenerics, Collections.emptyList()); Class<T> compiledClass = forceTranslatePythonBytecodeToGeneratorClass(pythonCompiledFunction, methodDescriptor, methodWithoutGenerics, false); return FunctionImplementor.createInstance(new PythonLikeTuple(), new PythonLikeDict(), new PythonLikeTuple(), pythonCompiledFunction.closure, PythonString.valueOf(compiledClass.getName()), compiledClass, PythonInterpreter.DEFAULT); } public static <T> Class<T> translatePythonBytecodeToClass(PythonCompiledFunction pythonCompiledFunction, Class<T> javaFunctionalInterfaceType) { MethodDescriptor methodDescriptor = new MethodDescriptor(getFunctionalInterfaceMethod(javaFunctionalInterfaceType)); return translatePythonBytecodeToClass(pythonCompiledFunction, methodDescriptor); } public static <T> Class<T> translatePythonBytecodeToClass(PythonCompiledFunction pythonCompiledFunction, Class<T> javaFunctionalInterfaceType, List<Class<?>> genericTypeArgumentList) { Method methodWithoutGenerics = getFunctionalInterfaceMethod(javaFunctionalInterfaceType); MethodDescriptor methodDescriptor = new MethodDescriptor(javaFunctionalInterfaceType, methodWithoutGenerics, genericTypeArgumentList); return translatePythonBytecodeToClass(pythonCompiledFunction, methodDescriptor, methodWithoutGenerics, false); } public static <T> Class<T> translatePythonBytecodeToClass(PythonCompiledFunction pythonCompiledFunction, MethodDescriptor methodDescriptor) { return translatePythonBytecodeToClass(pythonCompiledFunction, methodDescriptor, false); } public static <T> T translatePythonBytecodeToInstance(PythonCompiledFunction pythonCompiledFunction, MethodDescriptor methodDescriptor) { return translatePythonBytecodeToInstance(pythonCompiledFunction, methodDescriptor, false); } public static <T> T translatePythonBytecodeToInstance(PythonCompiledFunction pythonCompiledFunction, MethodDescriptor methodDescriptor, boolean isVirtual) { Class<T> compiledClass = translatePythonBytecodeToClass(pythonCompiledFunction, methodDescriptor, isVirtual); PythonLikeTuple annotationTuple = pythonCompiledFunction.typeAnnotations.entrySet() .stream() .map(entry -> PythonLikeTuple.fromItems(PythonString.valueOf(entry.getKey()), entry.getValue().type())) .collect(Collectors.toCollection(PythonLikeTuple::new)); return FunctionImplementor.createInstance(pythonCompiledFunction.defaultPositionalArguments, pythonCompiledFunction.defaultKeywordArguments, annotationTuple, pythonCompiledFunction.closure, PythonString.valueOf(compiledClass.getName()), compiledClass, PythonInterpreter.DEFAULT); } @SuppressWarnings("unchecked") public static <T> Class<T> translatePythonBytecodeToClass(PythonCompiledFunction pythonCompiledFunction, MethodDescriptor methodDescriptor, boolean isVirtual) { String maybeClassName = USER_PACKAGE_BASE + pythonCompiledFunction.getGeneratedClassBaseName(); int numberOfInstances = classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); ClassWriter classWriter = new JavaPythonClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, internalClassName, null, Type.getInternalName(Object.class), new String[] { methodDescriptor.getDeclaringClassInternalName() }); final boolean isPythonLikeFunction = methodDescriptor.getDeclaringClassInternalName().equals(Type.getInternalName(PythonLikeFunction.class)); classWriter.visitSource(pythonCompiledFunction.moduleFilePath, null); createFields(classWriter); createConstructor(classWriter, internalClassName); MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, methodDescriptor.getMethodName(), methodDescriptor.getMethodDescriptor(), null, null); translatePythonBytecodeToMethod(methodDescriptor, internalClassName, methodVisitor, pythonCompiledFunction, isPythonLikeFunction, isVirtual); classWriter.visitEnd(); writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); try { Class<T> compiledClass = (Class<T>) BuiltinTypes.asmClassLoader.loadClass(className); setStaticFields(compiledClass, pythonCompiledFunction); return compiledClass; } catch (ClassNotFoundException e) { throw new IllegalStateException("Impossible State: Unable to load generated class (" + className + ") despite it being just generated.", e); } } @SuppressWarnings("unchecked") public static <T> Class<T> translatePythonBytecodeToClass(PythonCompiledFunction pythonCompiledFunction, MethodDescriptor methodDescriptor, Method methodWithoutGenerics, boolean isVirtual) { String maybeClassName = USER_PACKAGE_BASE + pythonCompiledFunction.getGeneratedClassBaseName(); int numberOfInstances = classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); ClassWriter classWriter = new JavaPythonClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, internalClassName, null, Type.getInternalName(Object.class), new String[] { methodDescriptor.getDeclaringClassInternalName() }); final boolean isPythonLikeFunction = methodDescriptor.getDeclaringClassInternalName().equals(Type.getInternalName(PythonLikeFunction.class)); classWriter.visitSource(pythonCompiledFunction.moduleFilePath, null); createFields(classWriter); createConstructor(classWriter, internalClassName); MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, methodDescriptor.getMethodName(), methodDescriptor.getMethodDescriptor(), null, null); translatePythonBytecodeToMethod(methodDescriptor, internalClassName, methodVisitor, pythonCompiledFunction, isPythonLikeFunction, isVirtual); String withoutGenericsSignature = Type.getMethodDescriptor(methodWithoutGenerics); if (!withoutGenericsSignature.equals(methodDescriptor.getMethodDescriptor())) { methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, methodDescriptor.getMethodName(), withoutGenericsSignature, null, null); methodVisitor.visitCode(); visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); for (int i = 0; i < methodWithoutGenerics.getParameterCount(); i++) { Type parameterType = Type.getType(methodWithoutGenerics.getParameterTypes()[i]); methodVisitor.visitVarInsn(parameterType.getOpcode(Opcodes.ILOAD), i + 1); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getParameterTypes()[i].getInternalName()); } methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, internalClassName, methodDescriptor.getMethodName(), methodDescriptor.getMethodDescriptor(), false); methodVisitor.visitInsn(methodDescriptor.getReturnType().getOpcode(Opcodes.IRETURN)); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } classWriter.visitEnd(); writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); try { Class<T> compiledClass = (Class<T>) BuiltinTypes.asmClassLoader.loadClass(className); setStaticFields(compiledClass, pythonCompiledFunction); return compiledClass; } catch (ClassNotFoundException e) { throw new IllegalStateException("Impossible State: Unable to load generated class (" + className + ") despite it being just generated.", e); } } @SuppressWarnings("unchecked") public static <T> Class<T> translatePythonBytecodeToPythonWrapperClass(PythonCompiledFunction pythonCompiledFunction, OpaquePythonReference codeReference) { String maybeClassName = USER_PACKAGE_BASE + pythonCompiledFunction.getGeneratedClassBaseName(); int numberOfInstances = classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); ClassWriter classWriter = new JavaPythonClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, internalClassName, null, Type.getInternalName(Object.class), new String[] { Type.getInternalName(PythonLikeFunction.class) }); classWriter.visitSource(pythonCompiledFunction.moduleFilePath, null); createFields(classWriter); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, PYTHON_WRAPPER_CODE_STATIC_FIELD_NAME, Type.getDescriptor(OpaquePythonReference.class), null, null); classWriter.visitField(Modifier.PUBLIC | Modifier.FINAL, PYTHON_WRAPPER_FUNCTION_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonObjectWrapper.class), null, null); createPythonWrapperConstructor(classWriter, internalClassName); MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), null, null); methodVisitor.visitCode(); visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, PYTHON_WRAPPER_FUNCTION_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonObjectWrapper.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonObjectWrapper.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), false); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); classWriter.visitEnd(); writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); try { Class<T> compiledClass = (Class<T>) BuiltinTypes.asmClassLoader.loadClass(className); setStaticFields(compiledClass, pythonCompiledFunction); compiledClass.getField(PYTHON_WRAPPER_CODE_STATIC_FIELD_NAME).set(null, codeReference); return compiledClass; } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { throw new IllegalStateException("Impossible State: Unable to load generated class (" + className + ") despite it being just generated.", e); } } /** * Used for testing; force translate the python to a generator, even if it is not a generator */ @SuppressWarnings("unchecked") public static <T> Class<T> forceTranslatePythonBytecodeToGeneratorClass(PythonCompiledFunction pythonCompiledFunction, MethodDescriptor methodDescriptor, Method methodWithoutGenerics, boolean isVirtual) { String maybeClassName = USER_PACKAGE_BASE + pythonCompiledFunction.getGeneratedClassBaseName(); int numberOfInstances = classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); ClassWriter classWriter = new JavaPythonClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, internalClassName, null, Type.getInternalName(Object.class), new String[] { methodDescriptor.getDeclaringClassInternalName() }); classWriter.visitSource(pythonCompiledFunction.moduleFilePath, null); final boolean isPythonLikeFunction = methodDescriptor.getDeclaringClassInternalName().equals(Type.getInternalName(PythonLikeFunction.class)); createFields(classWriter); createConstructor(classWriter, internalClassName); MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, methodDescriptor.getMethodName(), methodDescriptor.getMethodDescriptor(), null, null); LocalVariableHelper localVariableHelper = new LocalVariableHelper(methodDescriptor.getParameterTypes(), pythonCompiledFunction); if (!isPythonLikeFunction) { // Need to convert Java parameters for (int i = 0; i < localVariableHelper.parameters.length; i++) { JavaPythonTypeConversionImplementor.copyParameter(methodVisitor, localVariableHelper, i); } } else { // Need to move Python parameters from the argument list + keyword list to their variable slots movePythonParametersToSlots(methodVisitor, internalClassName, pythonCompiledFunction, localVariableHelper); } for (int i = 0; i < localVariableHelper.getNumberOfBoundCells(); i++) { VariableImplementor.createCell(methodVisitor, localVariableHelper, i); } for (int i = 0; i < localVariableHelper.getNumberOfFreeCells(); i++) { VariableImplementor.setupFreeVariableCell(methodVisitor, internalClassName, localVariableHelper, i); } translateGeneratorBytecode(methodVisitor, methodDescriptor, internalClassName, localVariableHelper, pythonCompiledFunction); // TODO: Use actual python version String withoutGenericsSignature = Type.getMethodDescriptor(methodWithoutGenerics); if (!withoutGenericsSignature.equals(methodDescriptor.getMethodDescriptor())) { methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, methodDescriptor.getMethodName(), withoutGenericsSignature, null, null); methodVisitor.visitCode(); visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); for (int i = 0; i < methodWithoutGenerics.getParameterCount(); i++) { Type parameterType = Type.getType(methodWithoutGenerics.getParameterTypes()[i]); methodVisitor.visitVarInsn(parameterType.getOpcode(Opcodes.ILOAD), i + 1); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getParameterTypes()[i].getInternalName()); } methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, internalClassName, methodDescriptor.getMethodName(), methodDescriptor.getMethodDescriptor(), false); methodVisitor.visitInsn(methodDescriptor.getReturnType().getOpcode(Opcodes.IRETURN)); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } classWriter.visitEnd(); writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); try { Class<T> compiledClass = (Class<T>) BuiltinTypes.asmClassLoader.loadClass(className); setStaticFields(compiledClass, pythonCompiledFunction); return compiledClass; } catch (ClassNotFoundException e) { throw new IllegalStateException("Impossible State: Unable to load generated class (" + className + ") despite it being just generated.", e); } } private static void createConstructor(ClassWriter classWriter, String className) { // Empty constructor, for java code MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), null, null); methodVisitor.visitCode(); visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false); // Positional only and Positional/Keyword default arguments methodVisitor.visitInsn(Opcodes.DUP); CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); // Keyword only default arguments methodVisitor.visitInsn(Opcodes.DUP); CollectionImplementor.buildMap(PythonLikeDict.class, methodVisitor, 0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); // Annotation Directory as key/value tuple methodVisitor.visitInsn(Opcodes.DUP); CollectionImplementor.buildMap(PythonLikeDict.class, methodVisitor, 0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, ANNOTATION_DIRECTORY_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); // Free variable cells methodVisitor.visitInsn(Opcodes.DUP); CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, CELLS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); // Function name methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(className.replace('/', '.')); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonString.class), "valueOf", Type.getMethodDescriptor(Type.getType(PythonString.class), Type.getType(String.class)), false); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, QUALIFIED_NAME_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonString.class)); // Spec methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, ARGUMENT_SPEC_GETTER_STATIC_FIELD_NAME, Type.getDescriptor(BiFunction.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(BiFunction.class), "apply", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class), Type.getType(Object.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(ArgumentSpec.class)); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, ARGUMENT_SPEC_INSTANCE_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class)); // Interpreter methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(PythonInterpreter.class), "DEFAULT", Type.getDescriptor(PythonInterpreter.class)); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); // Full constructor, for MAKE_FUNCTION methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeTuple.class), Type.getType(PythonLikeDict.class), Type.getType(PythonLikeDict.class), Type.getType(PythonLikeTuple.class), Type.getType(PythonString.class), Type.getType(PythonInterpreter.class)), null, null); methodVisitor.visitCode(); visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false); // Positional only and Positional/Keyword default arguments methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); // Keyword only default arguments methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); // Annotation Directory as key/value tuple methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, ANNOTATION_DIRECTORY_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); // Free variable cells methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 4); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, CELLS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); // Function name methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 5); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, QUALIFIED_NAME_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonString.class)); // Spec methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, ARGUMENT_SPEC_GETTER_STATIC_FIELD_NAME, Type.getDescriptor(BiFunction.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(BiFunction.class), "apply", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class), Type.getType(Object.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(ArgumentSpec.class)); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, ARGUMENT_SPEC_INSTANCE_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class)); // Interpreter methodVisitor.visitVarInsn(Opcodes.ALOAD, 6); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } private static void createPythonWrapperConstructor(ClassWriter classWriter, String className) { // Empty constructor, for java code MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), null, null); methodVisitor.visitCode(); visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false); // Positional only and Positional/Keyword default arguments methodVisitor.visitInsn(Opcodes.DUP); CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); // Keyword only default arguments methodVisitor.visitInsn(Opcodes.DUP); CollectionImplementor.buildMap(PythonLikeDict.class, methodVisitor, 0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); // Annotation Directory as key/value tuple methodVisitor.visitInsn(Opcodes.DUP); CollectionImplementor.buildMap(PythonLikeDict.class, methodVisitor, 0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, ANNOTATION_DIRECTORY_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); // Free variable cells methodVisitor.visitInsn(Opcodes.DUP); CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, CELLS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); // Function name methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(className.replace('/', '.')); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonString.class), "valueOf", Type.getMethodDescriptor(Type.getType(PythonString.class), Type.getType(String.class)), false); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, QUALIFIED_NAME_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonString.class)); // Spec methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, ARGUMENT_SPEC_GETTER_STATIC_FIELD_NAME, Type.getDescriptor(BiFunction.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(BiFunction.class), "apply", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class), Type.getType(Object.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(ArgumentSpec.class)); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, ARGUMENT_SPEC_INSTANCE_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class)); // Interpreter methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(PythonInterpreter.class), "DEFAULT", Type.getDescriptor(PythonInterpreter.class)); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); // Function object methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, PYTHON_WRAPPER_CODE_STATIC_FIELD_NAME, Type.getDescriptor(OpaquePythonReference.class)); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, GLOBALS_MAP_STATIC_FIELD_NAME, Type.getDescriptor(Map.class)); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, CELLS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, QUALIFIED_NAME_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonString.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(CPythonBackedPythonInterpreter.class), "createPythonFunctionWrapper", Type.getMethodDescriptor(Type.getType(PythonObjectWrapper.class), Type.getType(OpaquePythonReference.class), Type.getType(Map.class), Type.getType(PythonLikeTuple.class), Type.getType(PythonString.class)), false); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, PYTHON_WRAPPER_FUNCTION_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonObjectWrapper.class)); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); // Full constructor, for MAKE_FUNCTION methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeTuple.class), Type.getType(PythonLikeDict.class), Type.getType(PythonLikeDict.class), Type.getType(PythonLikeTuple.class), Type.getType(PythonString.class), Type.getType(PythonInterpreter.class)), null, null); methodVisitor.visitCode(); visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false); // Positional only and Positional/Keyword default arguments methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); // Keyword only default arguments methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); // Annotation Directory as key/value tuple methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, ANNOTATION_DIRECTORY_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); // Free variable cells methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 4); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, CELLS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); // Function name methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 5); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, QUALIFIED_NAME_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonString.class)); // Spec methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, ARGUMENT_SPEC_GETTER_STATIC_FIELD_NAME, Type.getDescriptor(BiFunction.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(BiFunction.class), "apply", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class), Type.getType(Object.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(ArgumentSpec.class)); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, ARGUMENT_SPEC_INSTANCE_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class)); // Interpreter methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 6); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); // Function object methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, PYTHON_WRAPPER_CODE_STATIC_FIELD_NAME, Type.getDescriptor(OpaquePythonReference.class)); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, GLOBALS_MAP_STATIC_FIELD_NAME, Type.getDescriptor(Map.class)); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, CELLS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, QUALIFIED_NAME_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonString.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(CPythonBackedPythonInterpreter.class), "createPythonFunctionWrapper", Type.getMethodDescriptor(Type.getType(PythonObjectWrapper.class), Type.getType(OpaquePythonReference.class), Type.getType(Map.class), Type.getType(PythonLikeTuple.class), Type.getType(PythonString.class)), false); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, className, PYTHON_WRAPPER_FUNCTION_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonObjectWrapper.class)); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } public static void createFields(ClassWriter classWriter) { // Static fields classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, CONSTANTS_STATIC_FIELD_NAME, Type.getDescriptor(List.class), null, null); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, NAMES_STATIC_FIELD_NAME, Type.getDescriptor(List.class), null, null); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, VARIABLE_NAMES_STATIC_FIELD_NAME, Type.getDescriptor(List.class), null, null); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, GLOBALS_MAP_STATIC_FIELD_NAME, Type.getDescriptor(Map.class), null, null); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, CLASS_CELL_STATIC_FIELD_NAME, Type.getDescriptor(PythonLikeType.class), null, null); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, ARGUMENT_SPEC_GETTER_STATIC_FIELD_NAME, Type.getDescriptor(BiFunction.class), null, null); // Instance fields classWriter.visitField(Modifier.PRIVATE | Modifier.FINAL, INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class), null, null); classWriter.visitField(Modifier.PRIVATE | Modifier.FINAL, DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class), null, null); classWriter.visitField(Modifier.PRIVATE | Modifier.FINAL, DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class), null, null); classWriter.visitField(Modifier.PRIVATE | Modifier.FINAL, ANNOTATION_DIRECTORY_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class), null, null); classWriter.visitField(Modifier.PRIVATE | Modifier.FINAL, QUALIFIED_NAME_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonString.class), null, null); classWriter.visitField(Modifier.PRIVATE | Modifier.FINAL, CELLS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class), null, null); classWriter.visitField(Modifier.PUBLIC | Modifier.FINAL, ARGUMENT_SPEC_INSTANCE_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class), null, null); } static void setStaticFields(Class<?> compiledClass, PythonCompiledFunction pythonCompiledFunction) { try { compiledClass.getField(CONSTANTS_STATIC_FIELD_NAME).set(null, pythonCompiledFunction.co_constants); compiledClass.getField(GLOBALS_MAP_STATIC_FIELD_NAME).set(null, pythonCompiledFunction.globalsMap); compiledClass.getField(ARGUMENT_SPEC_GETTER_STATIC_FIELD_NAME).set(null, pythonCompiledFunction.getArgumentSpecMapper()); // Need to convert co_names to python strings (used in __getattribute__) List<PythonString> pythonNameList = new ArrayList<>(pythonCompiledFunction.co_names.size()); for (String name : pythonCompiledFunction.co_names) { pythonNameList.add(PythonString.valueOf(name)); } compiledClass.getField(NAMES_STATIC_FIELD_NAME).set(null, pythonNameList); List<PythonString> pythonVariableNameList = new ArrayList<>(pythonCompiledFunction.co_varnames.size()); for (String name : pythonCompiledFunction.co_varnames) { pythonVariableNameList.add(PythonString.valueOf(name)); } compiledClass.getField(VARIABLE_NAMES_STATIC_FIELD_NAME).set(null, pythonVariableNameList); // Class cell is set by PythonClassTranslator } catch (IllegalAccessException | NoSuchFieldException e) { throw new IllegalStateException("Impossible state: generated class (" + compiledClass + ") does not have static field \"" + CONSTANTS_STATIC_FIELD_NAME + "\"", e); } } public static List<Opcode> getOpcodeList(PythonCompiledFunction pythonCompiledFunction) { List<Opcode> opcodeList = new ArrayList<>(pythonCompiledFunction.instructionList.size()); for (PythonBytecodeInstruction instruction : pythonCompiledFunction.instructionList) { opcodeList.add(Opcode.lookupOpcodeForInstruction(instruction, pythonCompiledFunction.pythonVersion)); } return opcodeList; } public static StackMetadata getInitialStackMetadata(LocalVariableHelper localVariableHelper, MethodDescriptor method, boolean isVirtual) { StackMetadata initialStackMetadata = new StackMetadata(localVariableHelper); if (Type.getInternalName(PythonLikeFunction.class).equals(method.getDeclaringClassInternalName())) { return getPythonLikeFunctionInitialStackMetadata(localVariableHelper, initialStackMetadata); } for (int i = 0; i < method.getParameterTypes().length; i++) { Type type = method.getParameterTypes()[i]; try { Class<?> typeClass = Class.forName(type.getClassName(), false, BuiltinTypes.asmClassLoader); initialStackMetadata = initialStackMetadata.setLocalVariableValueSource(i, ValueSourceInfo.of(new OpcodeWithoutSource(), JavaPythonTypeConversionImplementor.getPythonLikeType(typeClass))); } catch (ClassNotFoundException e) { initialStackMetadata = initialStackMetadata.setLocalVariableValueSource(i, ValueSourceInfo.of(new OpcodeWithoutSource(), BuiltinTypes.BASE_TYPE)); } } if (isVirtual && method.getParameterTypes().length > 0) { try { Class<?> typeClass = Class.forName(method.getParameterTypes()[0].getClassName(), false, BuiltinTypes.asmClassLoader); initialStackMetadata = initialStackMetadata.setLocalVariableValueSource(0, ValueSourceInfo.of(new SelfOpcodeWithoutSource(), JavaPythonTypeConversionImplementor.getPythonLikeType(typeClass))); } catch (ClassNotFoundException e) { initialStackMetadata = initialStackMetadata.setLocalVariableValueSource(0, ValueSourceInfo.of(new SelfOpcodeWithoutSource(), BuiltinTypes.BASE_TYPE)); } } return initialStackMetadata; } private static StackMetadata getPythonLikeFunctionInitialStackMetadata(LocalVariableHelper localVariableHelper, StackMetadata initialStackMetadata) { for (int i = 0; i < localVariableHelper.getNumberOfLocalVariables(); i++) { initialStackMetadata = initialStackMetadata.setLocalVariableValueSource(i, ValueSourceInfo.of(new OpcodeWithoutSource(), BuiltinTypes.BASE_TYPE)); } for (int i = 0; i < localVariableHelper.getNumberOfCells(); i++) { initialStackMetadata = initialStackMetadata.setCellVariableValueSource(i, ValueSourceInfo.of(new OpcodeWithoutSource(), BuiltinTypes.BASE_TYPE)); } return initialStackMetadata; } public static PythonFunctionType getFunctionType(PythonCompiledFunction pythonCompiledFunction) { for (PythonBytecodeInstruction instruction : pythonCompiledFunction.instructionList) { var opcode = AbstractOpcode.lookupInstruction(instruction.opname()); if (opcode instanceof GeneratorOpDescriptor generatorInstruction) switch (generatorInstruction) { case GEN_START: case RETURN_GENERATOR: case YIELD_VALUE: case YIELD_FROM: return PythonFunctionType.GENERATOR; default: break; // Do nothing } } return PythonFunctionType.FUNCTION; } private static void translatePythonBytecodeToMethod(MethodDescriptor method, String className, MethodVisitor methodVisitor, PythonCompiledFunction pythonCompiledFunction, boolean isPythonLikeFunction, boolean isVirtual) { // Apply Method Adapters, which reorder try blocks and check the bytecode to ensure it valid methodVisitor = MethodVisitorAdapters.adapt(methodVisitor, method); for (int i = 0; i < method.getParameterTypes().length; i++) { if (!isPythonLikeFunction) { methodVisitor.visitParameter(pythonCompiledFunction.co_varnames.get(i), 0); } else { methodVisitor.visitParameter(null, 0); } } methodVisitor.visitCode(); visitGeneratedLineNumber(methodVisitor); Label start = new Label(); Label end = new Label(); methodVisitor.visitLabel(start); Map<Integer, Label> bytecodeCounterToLabelMap = new HashMap<>(); LocalVariableHelper localVariableHelper = new LocalVariableHelper(method.getParameterTypes(), pythonCompiledFunction); localVariableHelper.resetCallKeywords(methodVisitor); // The bytecode checker will see an empty slot in finally blocks without this (in particular, // when a try block finally handler is inside another try block). localVariableHelper.setupInitialStoredExceptionStacks(methodVisitor); if (!isPythonLikeFunction) { // Need to convert Java parameters for (int i = 0; i < localVariableHelper.parameters.length; i++) { JavaPythonTypeConversionImplementor.copyParameter(methodVisitor, localVariableHelper, i); } } else { // Need to move Python parameters from the argument list + keyword list to their variable slots movePythonParametersToSlots(methodVisitor, className, pythonCompiledFunction, localVariableHelper); } for (int i = 0; i < localVariableHelper.getNumberOfBoundCells(); i++) { VariableImplementor.createCell(methodVisitor, localVariableHelper, i); } for (int i = 0; i < localVariableHelper.getNumberOfFreeCells(); i++) { VariableImplementor.setupFreeVariableCell(methodVisitor, className, localVariableHelper, i); } Map<Integer, List<Runnable>> bytecodeIndexToArgumentorsMap = new HashMap<>(); FunctionMetadata functionMetadata = new FunctionMetadata(); functionMetadata.functionType = getFunctionType(pythonCompiledFunction); functionMetadata.method = method; functionMetadata.bytecodeCounterToCodeArgumenterList = bytecodeIndexToArgumentorsMap; functionMetadata.bytecodeCounterToLabelMap = bytecodeCounterToLabelMap; functionMetadata.methodVisitor = methodVisitor; functionMetadata.pythonCompiledFunction = pythonCompiledFunction; functionMetadata.className = className; if (functionMetadata.functionType == PythonFunctionType.GENERATOR) { translateGeneratorBytecode(methodVisitor, method, className, localVariableHelper, pythonCompiledFunction); return; } StackMetadata initialStackMetadata = getInitialStackMetadata(localVariableHelper, method, isVirtual); List<Opcode> opcodeList = getOpcodeList(pythonCompiledFunction); FlowGraph flowGraph = FlowGraph.createFlowGraph(functionMetadata, initialStackMetadata, opcodeList); List<StackMetadata> stackMetadataForOpcodeIndex = flowGraph.getStackMetadataForOperations(); writeInstructionsForOpcodes(functionMetadata, stackMetadataForOpcodeIndex, opcodeList); methodVisitor.visitLabel(end); for (int i = method.getParameterTypes().length; i < localVariableHelper.getNumberOfLocalVariables(); i++) { methodVisitor.visitLocalVariable(pythonCompiledFunction.co_varnames.get(i), Type.getDescriptor(PythonLikeObject.class), null, start, end, localVariableHelper.getPythonLocalVariableSlot(i)); } try { methodVisitor.visitMaxs(0, 0); } catch (Exception e) { throw new IllegalStateException("Invalid Java bytecode generated (this is a bug):\n" + pythonCompiledFunction.instructionList.stream() .map(PythonBytecodeInstruction::toString) .collect(Collectors.joining("\n")), e); } methodVisitor.visitEnd(); } public static void writeInstructionsForOpcodes(FunctionMetadata functionMetadata, List<StackMetadata> stackMetadataForOpcodeIndex, List<Opcode> opcodeList) { writeInstructionsForOpcodes(functionMetadata, stackMetadataForOpcodeIndex, opcodeList, ignored -> { }); } public static void writeInstructionsForOpcodes(FunctionMetadata functionMetadata, List<StackMetadata> stackMetadataForOpcodeIndex, List<Opcode> opcodeList, Consumer<PythonBytecodeInstruction> runAfterLabelAndBeforeArgumentors) { PythonCompiledFunction pythonCompiledFunction = functionMetadata.pythonCompiledFunction; MethodVisitor methodVisitor = functionMetadata.methodVisitor; Map<Integer, Label> bytecodeCounterToLabelMap = functionMetadata.bytecodeCounterToLabelMap; Map<Integer, List<Runnable>> bytecodeIndexToArgumentorsMap = functionMetadata.bytecodeCounterToCodeArgumenterList; Map<Integer, List<Runnable>> exceptionTableTryBlockMap = new HashMap<>(); Map<Integer, Label> exceptionTableStartLabelMap = new HashMap<>(); Map<Integer, Label> exceptionTableTargetLabelMap = new HashMap<>(); Set<Integer> tryBlockStartInstructionSet = new HashSet<>(); for (ExceptionBlock exceptionBlock : pythonCompiledFunction.co_exceptiontable.getEntries()) { if (exceptionBlock.blockStartInstructionInclusive == exceptionBlock.blockEndInstructionExclusive) { continue; // Empty try block range } tryBlockStartInstructionSet.add(exceptionBlock.blockStartInstructionInclusive); StackMetadata stackMetadata = stackMetadataForOpcodeIndex.get(exceptionBlock.blockStartInstructionInclusive); exceptionTableTryBlockMap.computeIfAbsent(exceptionBlock.blockStartInstructionInclusive, index -> new ArrayList<>()) .add(() -> { Label startLabel = exceptionTableStartLabelMap.computeIfAbsent(exceptionBlock.blockStartInstructionInclusive, offset -> new Label()); Label endLabel = bytecodeCounterToLabelMap.computeIfAbsent(exceptionBlock.blockEndInstructionExclusive, offset -> new Label()); Label targetLabel = exceptionTableTargetLabelMap.computeIfAbsent(exceptionBlock.targetInstruction, offset -> new Label()); if (exceptionBlock.blockStartInstructionInclusive > exceptionBlock.targetInstruction) { return; } functionMetadata.methodVisitor.visitTryCatchBlock(startLabel, endLabel, targetLabel, Type.getInternalName(PythonBaseException.class)); }); bytecodeIndexToArgumentorsMap.computeIfAbsent(exceptionBlock.targetInstruction, index -> new ArrayList<>()) .add(() -> ExceptionImplementor.startExceptBlock(functionMetadata, stackMetadata, exceptionBlock)); } // Do this after so the startExceptBlock code is before the code to store the stack for (Integer tryBlockStart : tryBlockStartInstructionSet) { StackMetadata stackMetadata = stackMetadataForOpcodeIndex.get(tryBlockStart); pythonCompiledFunction.co_exceptiontable.getEntries().stream() .filter(block -> block.blockStartInstructionInclusive == tryBlockStart) .forEach(exceptionBlock -> { bytecodeIndexToArgumentorsMap.computeIfAbsent(tryBlockStart, index -> new ArrayList<>()) .add(() -> StackManipulationImplementor.storeExceptionTableStack(functionMetadata, stackMetadata, exceptionBlock)); }); } var requiredNullVariableSet = new TreeSet<Integer>(); for (Opcode opcode : opcodeList) { if (opcode instanceof LoadFastAndClearOpcode loadAndClearOpcode) { requiredNullVariableSet.add(loadAndClearOpcode.getInstruction().arg()); } } for (var requiredNullVariable : requiredNullVariableSet) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitVarInsn(Opcodes.ASTORE, stackMetadataForOpcodeIndex.get(0).localVariableHelper.getPythonLocalVariableSlot(requiredNullVariable)); } for (int i = 0; i < opcodeList.size(); i++) { StackMetadata stackMetadata = stackMetadataForOpcodeIndex.get(i); PythonBytecodeInstruction instruction = pythonCompiledFunction.instructionList.get(i); if (exceptionTableTargetLabelMap.containsKey(instruction.offset())) { Label label = exceptionTableTargetLabelMap.get(instruction.offset()); methodVisitor.visitLabel(label); } exceptionTableTryBlockMap.getOrDefault(instruction.offset(), Collections.emptyList()).forEach(Runnable::run); if (instruction.isJumpTarget() || bytecodeCounterToLabelMap.containsKey(instruction.offset())) { Label label = bytecodeCounterToLabelMap.computeIfAbsent(instruction.offset(), offset -> new Label()); methodVisitor.visitLabel(label); } if (instruction.startsLine().isPresent()) { Label label = new Label(); methodVisitor.visitLabel(label); methodVisitor.visitLineNumber(instruction.startsLine().getAsInt(), label); } runAfterLabelAndBeforeArgumentors.accept(instruction); bytecodeIndexToArgumentorsMap.getOrDefault(instruction.offset(), Collections.emptyList()).forEach(Runnable::run); if (exceptionTableStartLabelMap.containsKey(instruction.offset())) { Label label = exceptionTableStartLabelMap.get(instruction.offset()); methodVisitor.visitLabel(label); } if (stackMetadata.isDeadCode()) { continue; } opcodeList.get(i).implement(functionMetadata, stackMetadata); } } private static void translateGeneratorBytecode(MethodVisitor methodVisitor, MethodDescriptor method, String internalClassName, LocalVariableHelper localVariableHelper, PythonCompiledFunction pythonCompiledFunction) { Class<?> generatorClass = PythonGeneratorTranslator.translateGeneratorFunction(pythonCompiledFunction); methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(generatorClass)); methodVisitor.visitInsn(Opcodes.DUP); Type[] javaParameterTypes = Stream.concat(Stream.of(Type.getType(PythonLikeTuple.class), Type.getType(PythonLikeDict.class), Type.getType(PythonLikeDict.class), Type.getType(PythonLikeTuple.class), Type.getType(PythonString.class), Type.getType(PythonInterpreter.class)), pythonCompiledFunction.getParameterTypes().stream() .map(type -> Type.getType(type.getJavaTypeDescriptor()))) .toArray(Type[]::new); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); // Positional only and Positional/Keyword default arguments methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitInsn(Opcodes.SWAP); // Keyword only default arguments methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); methodVisitor.visitInsn(Opcodes.SWAP); // Annotation Directory as key/value tuple methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, ANNOTATION_DIRECTORY_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); methodVisitor.visitInsn(Opcodes.SWAP); // Free variable cells methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, CELLS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitInsn(Opcodes.SWAP); // Function name methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, QUALIFIED_NAME_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonString.class)); methodVisitor.visitInsn(Opcodes.SWAP); // Interpreter methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); for (int i = 0; i < pythonCompiledFunction.totalArgCount(); i++) { localVariableHelper.readLocal(methodVisitor, i); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, javaParameterTypes[i + 6].getInternalName()); } methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(generatorClass), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, javaParameterTypes), false); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } private static void movePythonParametersToSlots(MethodVisitor methodVisitor, String internalClassName, PythonCompiledFunction pythonCompiledFunction, LocalVariableHelper localVariableHelper) { // Call {@link ArgumentSpec#extractArgumentList} to extract argument into a list methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, ARGUMENT_SPEC_INSTANCE_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(ArgumentSpec.class), "extractArgumentList", Type.getMethodDescriptor(Type.getType(List.class), Type.getType(List.class), Type.getType(Map.class)), false); for (int i = 0; i < pythonCompiledFunction.totalArgCount(); i++) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(i); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); methodVisitor.visitVarInsn(Opcodes.ASTORE, localVariableHelper.getPythonLocalVariableSlot(i)); } methodVisitor.visitInsn(Opcodes.POP); } /** * Used for debugging; prints the instruction when it is executed */ @SuppressWarnings("unused") private static void trace(MethodVisitor methodVisitor, PythonBytecodeInstruction instruction) { methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(System.class), "out", Type.getDescriptor(PrintStream.class)); methodVisitor.visitLdcInsn(instruction.toString()); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PrintStream.class), "println", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object.class)), false); } /** * Used for debugging; prints TOS */ @SuppressWarnings("unused") public static void print(MethodVisitor methodVisitor) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(System.class), "out", Type.getDescriptor(PrintStream.class)); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PrintStream.class), "println", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object.class)), false); } /** * Used for debugging; prints the entire stack */ @SuppressWarnings("unused") public static void printStack(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; int[] stackLocals = new int[stackMetadata.getStackSize()]; for (int i = stackLocals.length - 1; i >= 0; i--) { stackLocals[i] = localVariableHelper.newLocal(); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), stackLocals[i]); } methodVisitor.visitLdcInsn(stackLocals.length); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(PythonLikeObject.class)); for (int i = 0; i < stackLocals.length; i++) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(i); localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), stackLocals[i]); methodVisitor.visitInsn(Opcodes.AASTORE); } methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Arrays.class), "toString", Type.getMethodDescriptor(Type.getType(String.class), Type.getType(Object[].class)), false); print(methodVisitor); methodVisitor.visitInsn(Opcodes.POP); for (int i = 0; i < stackLocals.length; i++) { localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), stackLocals[i]); } for (int i = 0; i < stackLocals.length; i++) { localVariableHelper.freeLocal(); } } public static String getPythonBytecodeListing(PythonCompiledFunction pythonCompiledFunction) { StringBuilder out = new StringBuilder(); out.append("qualified_name = ").append(pythonCompiledFunction.qualifiedName).append("\n"); out.append("co_varnames = ").append(pythonCompiledFunction.co_varnames).append("\n"); out.append("co_cellvars = ").append(pythonCompiledFunction.co_cellvars).append("\n"); out.append("co_freevars = ").append(pythonCompiledFunction.co_freevars).append("\n"); out.append(pythonCompiledFunction.instructionList.stream() .map(PythonBytecodeInstruction::toString) .collect(Collectors.joining("\n"))); out.append("\nco_exceptiontable = ").append(pythonCompiledFunction.co_exceptiontable).append("\n"); return out.toString(); } public static void visitGeneratedLineNumber(MethodVisitor methodVisitor) { Label label = new Label(); methodVisitor.visitLabel(label); methodVisitor.visitLineNumber(0, label); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonClassTranslator.java
package ai.timefold.jpyinterpreter; import static ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator.ARGUMENT_SPEC_INSTANCE_FIELD_NAME; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.dag.FlowGraph; import ai.timefold.jpyinterpreter.implementors.DelegatingInterfaceImplementor; import ai.timefold.jpyinterpreter.implementors.JavaComparableImplementor; import ai.timefold.jpyinterpreter.implementors.JavaEqualsImplementor; import ai.timefold.jpyinterpreter.implementors.JavaHashCodeImplementor; import ai.timefold.jpyinterpreter.implementors.JavaInterfaceImplementor; import ai.timefold.jpyinterpreter.implementors.JavaPythonTypeConversionImplementor; import ai.timefold.jpyinterpreter.implementors.PythonConstantsImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.SelfOpcodeWithoutSource; import ai.timefold.jpyinterpreter.opcodes.controlflow.ReturnConstantValueOpcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.ReturnValueOpcode; import ai.timefold.jpyinterpreter.opcodes.object.DeleteAttrOpcode; import ai.timefold.jpyinterpreter.opcodes.object.LoadAttrOpcode; import ai.timefold.jpyinterpreter.opcodes.object.StoreAttrOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.LoadFastOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.CPythonBackedPythonLikeObject; import ai.timefold.jpyinterpreter.types.GeneratedFunctionMethodReference; import ai.timefold.jpyinterpreter.types.PythonJavaTypeMapping; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.NotImplementedError; import ai.timefold.jpyinterpreter.types.wrappers.JavaObjectWrapper; import ai.timefold.jpyinterpreter.types.wrappers.OpaquePythonReference; import ai.timefold.jpyinterpreter.util.JavaPythonClassWriter; import ai.timefold.jpyinterpreter.util.OverrideMethod; import ai.timefold.jpyinterpreter.util.arguments.ArgumentSpec; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.signature.SignatureVisitor; import org.objectweb.asm.signature.SignatureWriter; public class PythonClassTranslator { static Map<FunctionSignature, InterfaceDeclaration> functionSignatureToInterfaceName = new HashMap<>(); // $ is illegal in variables/methods in Python public static final String TYPE_FIELD_NAME = "$TYPE"; public static final String CPYTHON_TYPE_FIELD_NAME = "$CPYTHON_TYPE"; public static final String JAVA_METHOD_PREFIX = "$method$"; public static final String JAVA_METHOD_HOLDER_PREFIX = "$methodholder$"; public static final String PYTHON_JAVA_TYPE_MAPPING_PREFIX = "$pythonJavaTypeMapping"; public record PreparedClassInfo(PythonLikeType type, String className, String classInternalName) { } public static PreparedClassInfo getPreparedClassInfo(String pythonClassName, String module, String qualifiedName) { String maybeClassName = PythonBytecodeToJavaBytecodeTranslator.USER_PACKAGE_BASE + PythonCompiledClass.getGeneratedClassBaseName(module, qualifiedName); int numberOfInstances = PythonBytecodeToJavaBytecodeTranslator.classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); return new PreparedClassInfo(PythonLikeType.getTypeForNewClass(pythonClassName, internalClassName), className, internalClassName); } public static PythonLikeType translatePythonClass(PythonCompiledClass pythonCompiledClass) { return translatePythonClass(pythonCompiledClass, getPreparedClassInfo(pythonCompiledClass.className, pythonCompiledClass.module, pythonCompiledClass.qualifiedName)); } public static PythonLikeType translatePythonClass(PythonCompiledClass pythonCompiledClass, PreparedClassInfo preparedClassInfo) { var className = preparedClassInfo.className; var internalClassName = preparedClassInfo.classInternalName; Map<String, InterfaceDeclaration> instanceMethodNameToMethodDescriptor = new HashMap<>(); Set<PythonLikeType> superTypeSet; Set<JavaInterfaceImplementor> javaInterfaceImplementorSet = new HashSet<>(); for (Map.Entry<String, PythonCompiledFunction> instanceMethodEntry : pythonCompiledClass.instanceFunctionNameToPythonBytecode .entrySet()) { switch (instanceMethodEntry.getKey()) { case "__eq__": javaInterfaceImplementorSet.add(new JavaEqualsImplementor(internalClassName)); break; case "__hash__": javaInterfaceImplementorSet.add(new JavaHashCodeImplementor(internalClassName)); break; case "__lt__": case "__le__": case "__gt__": case "__ge__": javaInterfaceImplementorSet .add(new JavaComparableImplementor(internalClassName, instanceMethodEntry.getKey())); break; } } for (Class<?> javaInterface : pythonCompiledClass.javaInterfaces) { javaInterfaceImplementorSet.add( new DelegatingInterfaceImplementor(internalClassName, javaInterface, instanceMethodNameToMethodDescriptor)); } if (pythonCompiledClass.superclassList.isEmpty()) { superTypeSet = Set.of(CPythonBackedPythonLikeObject.CPYTHON_BACKED_OBJECT_TYPE); } else { superTypeSet = new LinkedHashSet<>(pythonCompiledClass.superclassList.size()); for (int i = 0; i < pythonCompiledClass.superclassList.size(); i++) { PythonLikeType superType = pythonCompiledClass.superclassList.get(i); if (superType == BuiltinTypes.BASE_TYPE || superType == null) { superTypeSet.add(CPythonBackedPythonLikeObject.CPYTHON_BACKED_OBJECT_TYPE); } else { superTypeSet.add(superType); } } } List<PythonLikeType> superTypeList = new ArrayList<>(superTypeSet); PythonLikeType pythonLikeType = preparedClassInfo.type; pythonLikeType.initializeNewType(superTypeList); PythonLikeType superClassType = superTypeList.get(0); Set<String> instanceAttributeSet = new HashSet<>(); pythonCompiledClass.instanceFunctionNameToPythonBytecode.values().forEach(instanceMethod -> { try { instanceAttributeSet.addAll(getReferencedSelfAttributes(instanceMethod)); } catch (UnsupportedOperationException e) { // silently ignore unsupported operations } catch (Exception e) { e.printStackTrace(); System.out.println("WARNING: Ignoring exception"); //e.printStackTrace(); //System.out.println("globals: " + instanceMethod.globalsMap); //System.out.println("co_constants: " + instanceMethod.co_constants); //System.out.println("co_names: " + instanceMethod.co_names); //System.out.println("co_varnames: " + instanceMethod.co_varnames); System.out.println("Instructions:"); System.out.println(instanceMethod.instructionList.stream() .map(PythonBytecodeInstruction::toString) .collect(Collectors.joining("\n"))); } }); List<JavaInterfaceImplementor> nonObjectInterfaceImplementors = javaInterfaceImplementorSet.stream() .filter(implementor -> !Object.class.equals(implementor.getInterfaceClass())) .toList(); String[] interfaces = new String[nonObjectInterfaceImplementors.size()]; for (int i = 0; i < nonObjectInterfaceImplementors.size(); i++) { interfaces[i] = Type.getInternalName(nonObjectInterfaceImplementors.get(i).getInterfaceClass()); } ClassWriter classWriter = new JavaPythonClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, internalClassName, null, superClassType.getJavaTypeInternalName(), interfaces); classWriter.visitSource(pythonCompiledClass.moduleFilePath, null); for (var annotation : AnnotationMetadata.getAnnotationListWithoutRepeatable(pythonCompiledClass.annotations)) { annotation.addAnnotationTo(classWriter); } pythonCompiledClass.staticAttributeNameToObject.forEach(pythonLikeType::$setAttribute); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, TYPE_FIELD_NAME, Type.getDescriptor(PythonLikeType.class), null, null); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, CPYTHON_TYPE_FIELD_NAME, Type.getDescriptor(PythonLikeType.class), null, null); for (Map.Entry<String, PythonLikeObject> staticAttributeEntry : pythonCompiledClass.staticAttributeNameToObject .entrySet()) { pythonLikeType.$setAttribute(staticAttributeEntry.getKey(), staticAttributeEntry.getValue()); } for (var attributeName : pythonCompiledClass.typeAnnotations.keySet()) { if (pythonLikeType.$getAttributeOrNull(attributeName) == null) { instanceAttributeSet.add(attributeName); } } for (int i = 0; i < pythonCompiledClass.pythonJavaTypeMappings.size(); i++) { classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, PYTHON_JAVA_TYPE_MAPPING_PREFIX + i, Type.getDescriptor(PythonJavaTypeMapping.class), null, null); } Map<String, PythonLikeType> attributeNameToTypeMap = new HashMap<>(); instanceAttributeSet.removeAll(pythonCompiledClass.staticAttributeDescriptorNames); try { var parentClass = superClassType.getJavaClass(); while (parentClass != Object.class) { for (Field field : parentClass.getFields()) { instanceAttributeSet.remove(field.getName()); } parentClass = parentClass.getSuperclass(); } } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } for (String attributeName : instanceAttributeSet) { var typeHint = pythonCompiledClass.typeAnnotations.getOrDefault(attributeName, TypeHint.withoutAnnotations(BuiltinTypes.BASE_TYPE)); PythonLikeType type = typeHint.type(); PythonLikeType javaGetterType = typeHint.javaGetterType(); if (type == null) { // null might be in __annotations__ type = BuiltinTypes.BASE_TYPE; } attributeNameToTypeMap.put(attributeName, type); FieldVisitor fieldVisitor; String javaFieldTypeDescriptor; String getterTypeDescriptor; String signature = null; boolean isJavaType; if (type.getJavaTypeInternalName().equals(Type.getInternalName(JavaObjectWrapper.class))) { javaFieldTypeDescriptor = Type.getDescriptor(type.getJavaObjectWrapperType()); getterTypeDescriptor = javaFieldTypeDescriptor; fieldVisitor = classWriter.visitField(Modifier.PUBLIC, getJavaFieldName(attributeName), javaFieldTypeDescriptor, null, null); isJavaType = true; } else { if (typeHint.genericArgs() != null) { var signatureWriter = new SignatureWriter(); visitSignature(typeHint, signatureWriter); signature = signatureWriter.toString(); } javaFieldTypeDescriptor = 'L' + type.getJavaTypeInternalName() + ';'; getterTypeDescriptor = javaGetterType.getJavaTypeDescriptor(); fieldVisitor = classWriter.visitField(Modifier.PUBLIC, getJavaFieldName(attributeName), javaFieldTypeDescriptor, signature, null); isJavaType = false; } fieldVisitor.visitEnd(); createJavaGetterSetter(classWriter, pythonCompiledClass, preparedClassInfo, attributeName, Type.getType(javaFieldTypeDescriptor), Type.getType(getterTypeDescriptor), signature, typeHint); FieldDescriptor fieldDescriptor = new FieldDescriptor(attributeName, getJavaFieldName(attributeName), internalClassName, javaFieldTypeDescriptor, type, true, isJavaType); pythonLikeType.addInstanceField(fieldDescriptor); } // No args constructor for creating instance of this class MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), null, null); methodVisitor.visitCode(); PythonBytecodeToJavaBytecodeTranslator.visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(PythonInterpreter.class), "DEFAULT", Type.getDescriptor(PythonInterpreter.class)); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, internalClassName, TYPE_FIELD_NAME, Type.getDescriptor(PythonLikeType.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClassType.getJavaTypeInternalName(), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonInterpreter.class), Type.getType(PythonLikeType.class)), false); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); // interpreter + type arg constructor for creating subclass of this class methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonInterpreter.class), Type.getType(PythonLikeType.class)), null, null); methodVisitor.visitParameter("subclassType", 0); methodVisitor.visitCode(); PythonBytecodeToJavaBytecodeTranslator.visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClassType.getJavaTypeInternalName(), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonInterpreter.class), Type.getType(PythonLikeType.class)), false); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); createGetAttribute(classWriter, internalClassName, superClassType.getJavaTypeInternalName(), instanceAttributeSet, attributeNameToTypeMap); createSetAttribute(classWriter, internalClassName, superClassType.getJavaTypeInternalName(), instanceAttributeSet, attributeNameToTypeMap); createDeleteAttribute(classWriter, internalClassName, superClassType.getJavaTypeInternalName(), instanceAttributeSet, attributeNameToTypeMap); for (Map.Entry<String, PythonCompiledFunction> instanceMethodEntry : pythonCompiledClass.instanceFunctionNameToPythonBytecode .entrySet()) { instanceMethodEntry.getValue().methodKind = PythonMethodKind.VIRTUAL_METHOD; createInstanceMethod(pythonLikeType, classWriter, internalClassName, instanceMethodEntry.getKey(), instanceMethodEntry.getValue(), instanceMethodNameToMethodDescriptor); } for (Map.Entry<String, PythonCompiledFunction> staticMethodEntry : pythonCompiledClass.staticFunctionNameToPythonBytecode .entrySet()) { staticMethodEntry.getValue().methodKind = PythonMethodKind.STATIC_METHOD; createStaticMethod(pythonLikeType, classWriter, internalClassName, staticMethodEntry.getKey(), staticMethodEntry.getValue()); } for (Map.Entry<String, PythonCompiledFunction> classMethodEntry : pythonCompiledClass.classFunctionNameToPythonBytecode .entrySet()) { classMethodEntry.getValue().methodKind = PythonMethodKind.CLASS_METHOD; createClassMethod(pythonLikeType, classWriter, internalClassName, classMethodEntry.getKey(), classMethodEntry.getValue()); } boolean isCpythonBacked; try { isCpythonBacked = CPythonBackedPythonLikeObject.class.isAssignableFrom(superClassType.getJavaClass()); } catch (ClassNotFoundException e) { isCpythonBacked = false; } if (isCpythonBacked) { createCPythonOperationMethods(classWriter, internalClassName, superClassType.getJavaTypeInternalName(), attributeNameToTypeMap); } javaInterfaceImplementorSet.forEach(implementor -> implementor.implement(classWriter, pythonCompiledClass)); classWriter.visitEnd(); PythonBytecodeToJavaBytecodeTranslator.writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); pythonLikeType.$setAttribute("__name__", PythonString.valueOf(pythonCompiledClass.className)); pythonLikeType.$setAttribute("__qualname__", PythonString.valueOf(pythonCompiledClass.qualifiedName)); pythonLikeType.$setAttribute("__module__", PythonString.valueOf(pythonCompiledClass.module)); PythonLikeDict annotations = new PythonLikeDict(); pythonCompiledClass.typeAnnotations .forEach((name, type) -> annotations.put(PythonString.valueOf(name), type.type())); pythonLikeType.$setAttribute("__annotations__", annotations); PythonLikeTuple mro = new PythonLikeTuple(); mro.addAll(superTypeList); pythonLikeType.$setAttribute("__mro__", mro); Class<? extends PythonLikeObject> generatedClass; try { generatedClass = (Class<? extends PythonLikeObject>) BuiltinTypes.asmClassLoader.loadClass(className); generatedClass.getField(TYPE_FIELD_NAME).set(null, pythonLikeType); generatedClass.getField(CPYTHON_TYPE_FIELD_NAME).set(null, pythonCompiledClass.binaryType); for (int i = 0; i < pythonCompiledClass.pythonJavaTypeMappings.size(); i++) { generatedClass.getField(PYTHON_JAVA_TYPE_MAPPING_PREFIX + i) .set(null, pythonCompiledClass.pythonJavaTypeMappings.get(i)); } } catch (ClassNotFoundException e) { throw new IllegalStateException("Impossible State: Unable to load generated class (" + className + ") despite it being just generated.", e); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalStateException("Impossible State: could not access type static field for generated class (" + className + ").", e); } Class<?> initFunctionClass = null; for (Map.Entry<String, PythonCompiledFunction> instanceMethodEntry : pythonCompiledClass.instanceFunctionNameToPythonBytecode .entrySet()) { InterfaceDeclaration interfaceDeclaration = getInterfaceForInstancePythonFunction(internalClassName, instanceMethodEntry.getValue()); Class<?> createdFunctionClass = createBytecodeForMethodAndSetOnClass(className, pythonLikeType, pythonCompiledClass.binaryType, generatedClass, instanceMethodEntry, interfaceDeclaration, PythonMethodKind.VIRTUAL_METHOD); if (instanceMethodEntry.getKey().equals("__init__")) { initFunctionClass = createdFunctionClass; } } for (Map.Entry<String, PythonCompiledFunction> staticMethodEntry : pythonCompiledClass.staticFunctionNameToPythonBytecode .entrySet()) { InterfaceDeclaration interfaceDeclaration = getInterfaceForPythonFunction(staticMethodEntry.getValue()); createBytecodeForMethodAndSetOnClass(className, pythonLikeType, pythonCompiledClass.binaryType, generatedClass, staticMethodEntry, interfaceDeclaration, PythonMethodKind.STATIC_METHOD); } for (Map.Entry<String, PythonCompiledFunction> classMethodEntry : pythonCompiledClass.classFunctionNameToPythonBytecode .entrySet()) { InterfaceDeclaration interfaceDeclaration = getInterfaceForClassPythonFunction(classMethodEntry.getValue()); createBytecodeForMethodAndSetOnClass(className, pythonLikeType, pythonCompiledClass.binaryType, generatedClass, classMethodEntry, interfaceDeclaration, PythonMethodKind.CLASS_METHOD); } pythonLikeType.setConstructor(createConstructor(internalClassName, pythonCompiledClass.instanceFunctionNameToPythonBytecode.get("__init__"), generatedClass)); PythonOverloadImplementor.createDispatchesFor(pythonLikeType); return pythonLikeType; } private static void visitSignature(TypeHint typeHint, SignatureVisitor signatureVisitor) { signatureVisitor.visitClassType(typeHint.type().getJavaTypeInternalName()); if (typeHint.genericArgs() != null) { for (TypeHint genericArg : typeHint.genericArgs()) { visitSignature(genericArg, signatureVisitor.visitTypeArgument('=')); } } signatureVisitor.visitEnd(); } public static void setSelfStaticInstances(PythonCompiledClass pythonCompiledClass, Class<?> generatedClass, PythonLikeType pythonLikeType, Map<Number, PythonLikeObject> instanceMap) { if (!CPythonBackedPythonLikeObject.class.isAssignableFrom(generatedClass)) { return; } pythonCompiledClass.staticAttributeNameToClassInstance.forEach((attributeName, instancePointer) -> { try { CPythonBackedPythonLikeObject objectInstance = (CPythonBackedPythonLikeObject) generatedClass.getConstructor().newInstance(); Number pythonReferenceId = CPythonBackedPythonInterpreter.getPythonReferenceId(instancePointer); instanceMap.put(pythonReferenceId, objectInstance); objectInstance.$setCPythonReference(instancePointer); objectInstance.$setInstanceMap(instanceMap); objectInstance.$readFieldsFromCPythonReference(); pythonLikeType.$setAttribute(attributeName, objectInstance); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new RuntimeException("Unable to construct instance of class (" + generatedClass + ")", e); } }); } public static String getJavaFieldName(String pythonFieldName) { return pythonFieldName; } public static String getPythonFieldName(String javaFieldName) { return javaFieldName; } public static String getJavaMethodName(String pythonMethodName) { return JAVA_METHOD_PREFIX + pythonMethodName; } public static String getJavaMethodHolderName(String pythonMethodName) { return JAVA_METHOD_HOLDER_PREFIX + pythonMethodName; } public static String getPythonMethodName(String javaMethodName) { return javaMethodName.substring(JAVA_METHOD_PREFIX.length()); } private static Class<?> createBytecodeForMethodAndSetOnClass(String className, PythonLikeType pythonLikeType, PythonLikeType cPythonType, Class<? extends PythonLikeObject> generatedClass, Map.Entry<String, PythonCompiledFunction> methodEntry, InterfaceDeclaration interfaceDeclaration, PythonMethodKind pythonMethodKind) { Class<?> functionClass; Object functionInstance; try { functionInstance = PythonBytecodeToJavaBytecodeTranslator.translatePythonBytecodeToInstance(methodEntry.getValue(), new MethodDescriptor(interfaceDeclaration.interfaceName, MethodDescriptor.MethodType.INTERFACE, "invoke", interfaceDeclaration.methodDescriptor), pythonMethodKind == PythonMethodKind.VIRTUAL_METHOD); functionClass = functionInstance.getClass(); functionClass.getField(PythonBytecodeToJavaBytecodeTranslator.CLASS_CELL_STATIC_FIELD_NAME).set(null, pythonLikeType); } catch (Exception e) { functionClass = createPythonWrapperMethod(methodEntry.getKey(), methodEntry.getValue(), interfaceDeclaration, pythonMethodKind == PythonMethodKind.VIRTUAL_METHOD); try { functionInstance = functionClass.getConstructor(PythonLikeType.class).newInstance(cPythonType); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { throw new IllegalStateException( "Cannot create instance of Python native wrapper despite it being just generated", ex); } } try { PythonLikeObject translatedPythonMethodWrapper; PythonCompiledFunction function = methodEntry.getValue(); pythonLikeType.clearMethod(methodEntry.getKey()); String javaMethodDescriptor = Arrays.stream(generatedClass.getDeclaredMethods()) .filter(method -> method.getName().equals(getJavaMethodName(methodEntry.getKey())) && !method.isAnnotationPresent(OverrideMethod.class)) .map(Type::getMethodDescriptor) .findFirst().orElseThrow(); ArgumentSpec<?> argumentSpec = function.getArgumentSpecMapper() .apply(function.defaultPositionalArguments, function.defaultKeywordArguments); switch (pythonMethodKind) { case VIRTUAL_METHOD: translatedPythonMethodWrapper = new GeneratedFunctionMethodReference(functionInstance, functionClass.getMethods()[0], Map.of(), PythonLikeFunction.getFunctionType()); pythonLikeType.addMethod(methodEntry.getKey(), argumentSpec.asPythonFunctionSignature(className.replace('.', '/'), getJavaMethodName(methodEntry.getKey()), javaMethodDescriptor)); break; case STATIC_METHOD: translatedPythonMethodWrapper = new GeneratedFunctionMethodReference(functionInstance, functionClass.getMethods()[0], Map.of(), PythonLikeFunction.getStaticFunctionType()); pythonLikeType.addMethod(methodEntry.getKey(), argumentSpec.asStaticPythonFunctionSignature(className.replace('.', '/'), getJavaMethodName(methodEntry.getKey()), javaMethodDescriptor)); break; case CLASS_METHOD: translatedPythonMethodWrapper = new GeneratedFunctionMethodReference(functionInstance, functionClass.getMethods()[0], Map.of(), PythonLikeFunction.getClassFunctionType()); pythonLikeType.addMethod(methodEntry.getKey(), argumentSpec.asClassPythonFunctionSignature(className.replace('.', '/'), getJavaMethodName(methodEntry.getKey()), javaMethodDescriptor)); break; default: throw new IllegalStateException("Unhandled case: " + pythonMethodKind); } generatedClass.getField(getJavaMethodHolderName(methodEntry.getKey())) .set(null, functionInstance); pythonLikeType.$setAttribute(methodEntry.getKey(), translatedPythonMethodWrapper); return functionClass; } catch (IllegalAccessException | NoSuchFieldException e) { throw new IllegalStateException("Impossible State: could not access method (" + methodEntry.getKey() + ") static field for generated class (" + className + ").", e); } } private static Class<?> createPythonWrapperMethod(String methodName, PythonCompiledFunction pythonCompiledFunction, InterfaceDeclaration interfaceDeclaration, boolean isVirtual) { String maybeClassName = PythonBytecodeToJavaBytecodeTranslator.GENERATED_PACKAGE_BASE + pythonCompiledFunction.getGeneratedClassBaseName() + "$$Wrapper"; int numberOfInstances = PythonBytecodeToJavaBytecodeTranslator.classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); ClassWriter classWriter = new JavaPythonClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, internalClassName, null, Type.getInternalName(Object.class), new String[] { interfaceDeclaration.interfaceName }); classWriter.visitSource("<generated signature>", null); classWriter.visitField(Modifier.PUBLIC | Modifier.FINAL, "$binaryType", Type.getDescriptor(PythonLikeType.class), null, null); classWriter.visitField(Modifier.STATIC | Modifier.PUBLIC, ARGUMENT_SPEC_INSTANCE_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class), null, null); // Constructor that takes a PythonLikeType MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeType.class)), null, null); methodVisitor.visitCode(); PythonBytecodeToJavaBytecodeTranslator.visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, "$binaryType", Type.getDescriptor(PythonLikeType.class)); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); // Interface method methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "invoke", interfaceDeclaration.methodDescriptor, null, null); for (int i = 0; i < pythonCompiledFunction.totalArgCount(); i++) { methodVisitor.visitParameter("parameter" + i, 0); } methodVisitor.visitCode(); PythonBytecodeToJavaBytecodeTranslator.visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, "$binaryType", Type.getDescriptor(PythonLikeType.class)); methodVisitor.visitLdcInsn(methodName); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrError", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeFunction.class)); methodVisitor.visitLdcInsn(pythonCompiledFunction.totalArgCount()); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(Object.class)); for (int i = 0; i < pythonCompiledFunction.totalArgCount(); i++) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(i); methodVisitor.visitVarInsn(Opcodes.ALOAD, i + 1); methodVisitor.visitInsn(Opcodes.AASTORE); } methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Arrays.class), "asList", Type.getMethodDescriptor(Type.getType(List.class), Type.getType(Object[].class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getReturnType(interfaceDeclaration.methodDescriptor).getInternalName()); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); classWriter.visitEnd(); PythonBytecodeToJavaBytecodeTranslator.writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); try { return BuiltinTypes.asmClassLoader.loadClass(className); } catch (ClassNotFoundException e) { throw new IllegalStateException("Cannot load class " + className + " despite it being just generated", e); } } private static PythonLikeFunction createConstructor(String classInternalName, PythonCompiledFunction initFunction, Class<?> typeGeneratedClass) { String maybeClassName = PythonBytecodeToJavaBytecodeTranslator.GENERATED_PACKAGE_BASE + classInternalName.replace('/', '.') + "$$Constructor"; int numberOfInstances = PythonBytecodeToJavaBytecodeTranslator.classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String constructorClassName = maybeClassName; String constructorInternalClassName = constructorClassName.replace('.', '/'); ClassWriter classWriter = new JavaPythonClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, constructorInternalClassName, null, Type.getInternalName(Object.class), new String[] { Type.getInternalName(PythonLikeFunction.class) }); classWriter.visitSource(initFunction != null ? initFunction.moduleFilePath : "<unknown>", null); classWriter.visitField(Modifier.STATIC | Modifier.PUBLIC, ARGUMENT_SPEC_INSTANCE_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class), null, null); MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), null, null); methodVisitor.visitCode(); PythonBytecodeToJavaBytecodeTranslator.visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); Type generatedClassType = Type.getType('L' + classInternalName + ';'); methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), null, null); methodVisitor.visitCode(); PythonBytecodeToJavaBytecodeTranslator.visitGeneratedLineNumber(methodVisitor); methodVisitor.visitTypeInsn(Opcodes.NEW, classInternalName); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, classInternalName, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); if (initFunction != null) { Label start = new Label(); methodVisitor.visitLabel(start); methodVisitor.visitLineNumber(initFunction.getFirstLine(), start); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, constructorInternalClassName, ARGUMENT_SPEC_INSTANCE_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(ArgumentSpec.class), "extractArgumentList", Type.getMethodDescriptor(Type.getType(List.class), Type.getType(List.class), Type.getType(Map.class)), false); List<PythonLikeType> initParameterTypes = initFunction.getParameterTypes(); for (int i = 1; i < initParameterTypes.size(); i++) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(i - 1); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, initParameterTypes.get(i).getJavaTypeInternalName()); methodVisitor.visitInsn(Opcodes.SWAP); } methodVisitor.visitInsn(Opcodes.POP); Type[] parameterTypes = new Type[initFunction.totalArgCount() - 1]; List<PythonLikeType> parameterTypeAnnotations = initFunction.getParameterTypes(); for (int i = 1; i < parameterTypeAnnotations.size(); i++) { parameterTypes[i - 1] = Type.getType('L' + parameterTypeAnnotations.get(i).getJavaTypeInternalName() + ';'); } Type returnType = getVirtualFunctionReturnType(initFunction); String initMethodDescriptor = Type.getMethodDescriptor(returnType, parameterTypes); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classInternalName, getJavaMethodName("__init__"), initMethodDescriptor, false); methodVisitor.visitInsn(Opcodes.POP); } methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); classWriter.visitEnd(); PythonBytecodeToJavaBytecodeTranslator.writeClassOutput(BuiltinTypes.classNameToBytecode, constructorClassName, classWriter.toByteArray()); try { @SuppressWarnings("unchecked") Class<? extends PythonLikeFunction> generatedClass = (Class<? extends PythonLikeFunction>) BuiltinTypes.asmClassLoader.loadClass(constructorClassName); if (initFunction != null) { Object method = typeGeneratedClass.getField(getJavaMethodHolderName("__init__")).get(null); ArgumentSpec spec = (ArgumentSpec) method.getClass().getField(ARGUMENT_SPEC_INSTANCE_FIELD_NAME).get(method); generatedClass.getField(ARGUMENT_SPEC_INSTANCE_FIELD_NAME).set(null, spec); } return generatedClass.getConstructor().newInstance(); } catch (ClassNotFoundException | RuntimeException | InstantiationException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | NoSuchFieldException e) { throw new IllegalStateException("Impossible State: Unable to load generated class (" + constructorClassName + ") despite it being just generated.", e); } } private record MatchedMapping(int index, PythonJavaTypeMapping<?, ?> pythonJavaTypeMapping) { } private static void createJavaGetterSetter(ClassWriter classWriter, PythonCompiledClass pythonCompiledClass, PreparedClassInfo preparedClassInfo, String attributeName, Type attributeType, Type getterType, String signature, TypeHint typeHint) { MatchedMapping matchedMapping = null; for (int i = 0; i < pythonCompiledClass.pythonJavaTypeMappings.size(); i++) { var mapping = pythonCompiledClass.pythonJavaTypeMappings.get(i); if (mapping.getPythonType().equals(typeHint.javaGetterType())) { matchedMapping = new MatchedMapping(i, mapping); getterType = Type.getType(mapping.getJavaType()); } } createJavaGetter(classWriter, preparedClassInfo, matchedMapping, attributeName, attributeType, getterType, signature, typeHint); createJavaSetter(classWriter, preparedClassInfo, matchedMapping, attributeName, attributeType, getterType, signature, typeHint); } private static void createJavaGetter(ClassWriter classWriter, PreparedClassInfo preparedClassInfo, MatchedMapping matchedMapping, String attributeName, Type attributeType, Type getterType, String signature, TypeHint typeHint) { var typeOverride = typeHint.getOverrideTypeDescriptor(); var isTypeOverridden = typeOverride != null; if (isTypeOverridden) { getterType = Type.getType(typeOverride); } var getterName = "get" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1); if (signature != null && Objects.equals(attributeType, getterType)) { signature = "()" + signature; } var getterVisitor = classWriter.visitMethod(Modifier.PUBLIC, getterName, Type.getMethodDescriptor(getterType), signature, null); var maxStack = 1; for (var annotation : AnnotationMetadata.getAnnotationListWithoutRepeatable(typeHint.annotationList())) { annotation.addAnnotationTo(getterVisitor); } getterVisitor.visitCode(); if (isTypeOverridden && !Objects.equals(attributeType, getterType)) { JavaPythonTypeConversionImplementor.loadTypeClass(getterType, getterVisitor); } getterVisitor.visitVarInsn(Opcodes.ALOAD, 0); getterVisitor.visitFieldInsn(Opcodes.GETFIELD, preparedClassInfo.classInternalName, attributeName, attributeType.getDescriptor()); if (typeHint.type().isInstance(PythonNone.INSTANCE)) { maxStack = 3; getterVisitor.visitInsn(Opcodes.DUP); PythonConstantsImplementor.loadNone(getterVisitor); Label returnLabel = new Label(); getterVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, returnLabel); // field is None, so we want Java to see it as null getterVisitor.visitInsn(Opcodes.POP); getterVisitor.visitInsn(Opcodes.ACONST_NULL); getterVisitor.visitLabel(returnLabel); // If branch is taken, stack is field // If branch is not taken, stack is null } if (!Objects.equals(attributeType, getterType)) { if (matchedMapping != null) { getterVisitor.visitInsn(Opcodes.DUP); getterVisitor.visitInsn(Opcodes.ACONST_NULL); Label skipMapping = new Label(); getterVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, skipMapping); getterVisitor.visitFieldInsn(Opcodes.GETSTATIC, preparedClassInfo.classInternalName, PYTHON_JAVA_TYPE_MAPPING_PREFIX + matchedMapping.index, Type.getDescriptor(PythonJavaTypeMapping.class)); getterVisitor.visitInsn(Opcodes.SWAP); getterVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonJavaTypeMapping.class), "toJavaObject", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class)), true); getterVisitor.visitLabel(skipMapping); } if (isTypeOverridden) { getterVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "convertPythonObjectToJavaType", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Class.class), Type.getType(PythonLikeObject.class)), false); } if (getterType.getSort() == Type.OBJECT) { getterVisitor.visitTypeInsn(Opcodes.CHECKCAST, getterType.getInternalName()); } else { JavaPythonTypeConversionImplementor.unboxBoxedPrimitiveType(getterType, getterVisitor); } } getterVisitor.visitInsn(getterType.getOpcode(Opcodes.IRETURN)); getterVisitor.visitMaxs(maxStack, 0); getterVisitor.visitEnd(); } private static void createJavaSetter(ClassWriter classWriter, PreparedClassInfo preparedClassInfo, MatchedMapping matchedMapping, String attributeName, Type attributeType, Type setterType, String signature, TypeHint typeHint) { var setterName = "set" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1); var typeOverride = typeHint.getOverrideTypeDescriptor(); var isTypeOverridden = typeOverride != null; if (isTypeOverridden) { setterType = Type.getType(typeOverride); } if (signature != null && Objects.equals(attributeType, setterType)) { signature = "(" + signature + ")V"; } var setterVisitor = classWriter.visitMethod(Modifier.PUBLIC, setterName, Type.getMethodDescriptor(Type.VOID_TYPE, setterType), signature, null); var maxStack = 2; setterVisitor.visitCode(); setterVisitor.visitVarInsn(Opcodes.ALOAD, 0); setterVisitor.visitVarInsn(setterType.getOpcode(Opcodes.ILOAD), 1); if (setterType.getSort() != Type.OBJECT) { JavaPythonTypeConversionImplementor.boxPrimitiveType(setterType, setterVisitor); } if (typeHint.type().isInstance(PythonNone.INSTANCE)) { maxStack = 4; // We want to replace null with None setterVisitor.visitInsn(Opcodes.DUP); setterVisitor.visitInsn(Opcodes.ACONST_NULL); Label setFieldLabel = new Label(); setterVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, setFieldLabel); // set value is null, so we want Python to see it as None setterVisitor.visitInsn(Opcodes.POP); PythonConstantsImplementor.loadNone(setterVisitor); setterVisitor.visitLabel(setFieldLabel); // If branch is taken, stack is (non-null instance) // If branch is not taken, stack is None } if (!Objects.equals(attributeType, setterType)) { if (matchedMapping != null) { setterVisitor.visitVarInsn(Opcodes.ALOAD, 1); setterVisitor.visitInsn(Opcodes.ACONST_NULL); Label skipMapping = new Label(); setterVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, skipMapping); setterVisitor.visitFieldInsn(Opcodes.GETSTATIC, preparedClassInfo.classInternalName, PYTHON_JAVA_TYPE_MAPPING_PREFIX + matchedMapping.index, Type.getDescriptor(PythonJavaTypeMapping.class)); setterVisitor.visitInsn(Opcodes.SWAP); setterVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonJavaTypeMapping.class), "toPythonObject", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class)), true); setterVisitor.visitLabel(skipMapping); } if (isTypeOverridden) { setterVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "wrapJavaObject", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(Object.class)), false); } setterVisitor.visitTypeInsn(Opcodes.CHECKCAST, attributeType.getInternalName()); } setterVisitor.visitFieldInsn(Opcodes.PUTFIELD, preparedClassInfo.classInternalName, attributeName, attributeType.getDescriptor()); setterVisitor.visitInsn(Opcodes.RETURN); setterVisitor.visitMaxs(maxStack, 0); setterVisitor.visitEnd(); } private static void addAnnotationsToMethod(PythonCompiledFunction function, MethodVisitor methodVisitor) { var returnTypeHint = function.typeAnnotations.get("return"); if (returnTypeHint != null) { for (var annotation : AnnotationMetadata.getAnnotationListWithoutRepeatable(returnTypeHint.annotationList())) { annotation.addAnnotationTo(methodVisitor); } } } private static void createInstanceMethod(PythonLikeType pythonLikeType, ClassWriter classWriter, String internalClassName, String methodName, PythonCompiledFunction function, Map<String, InterfaceDeclaration> instanceMethodNameToMethodDescriptor) { InterfaceDeclaration interfaceDeclaration = getInterfaceForInstancePythonFunction(internalClassName, function); String interfaceDescriptor = interfaceDeclaration.descriptor(); String javaMethodName = getJavaMethodName(methodName); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, getJavaMethodHolderName(methodName), interfaceDescriptor, null, null); instanceMethodNameToMethodDescriptor.put(methodName, interfaceDeclaration); Type returnType = getVirtualFunctionReturnType(function); List<PythonLikeType> parameterPythonTypeList = function.getParameterTypes(); Type[] javaParameterTypes = new Type[Math.max(0, function.totalArgCount() - 1)]; for (int i = 1; i < function.totalArgCount(); i++) { javaParameterTypes[i - 1] = Type.getType(parameterPythonTypeList.get(i).getJavaTypeDescriptor()); } String javaMethodDescriptor = Type.getMethodDescriptor(returnType, javaParameterTypes); String signature = getFunctionSignature(function, javaMethodDescriptor); MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, javaMethodName, javaMethodDescriptor, signature, null); createInstanceOrStaticMethodBody(internalClassName, methodName, javaParameterTypes, interfaceDeclaration.methodDescriptor, function, interfaceDeclaration.interfaceName, interfaceDescriptor, methodVisitor); Set<String> overrides = new HashSet<>(); for (var parent : pythonLikeType.getParentList()) { try { var parentType = parent.getJavaClass(); for (var method : parentType.getMethods()) { var parentMethodDescriptor = Type.getMethodDescriptor(method); if (method.getName().equals(javaMethodName) && !Modifier.isStatic(method.getModifiers()) && !parentMethodDescriptor.equals(javaMethodDescriptor) && !overrides.contains(parentMethodDescriptor)) { overrides.add(parentMethodDescriptor); createOverrideMethod(classWriter, internalClassName, method, javaMethodDescriptor, javaParameterTypes); } } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } pythonLikeType.addMethod(methodName, new PythonFunctionSignature(new MethodDescriptor(internalClassName, MethodDescriptor.MethodType.VIRTUAL, javaMethodName, javaMethodDescriptor), function.getReturnType().orElse(BuiltinTypes.BASE_TYPE), function.totalArgCount() > 0 ? function.getParameterTypes().subList(1, function.getParameterTypes().size()) : Collections.emptyList())); } private static void createStaticMethod(PythonLikeType pythonLikeType, ClassWriter classWriter, String internalClassName, String methodName, PythonCompiledFunction function) { InterfaceDeclaration interfaceDeclaration = getInterfaceForPythonFunction(function); String interfaceDescriptor = 'L' + interfaceDeclaration.interfaceName + ';'; String javaMethodName = getJavaMethodName(methodName); String signature = getFunctionSignature(function, function.getAsmMethodDescriptorString()); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, getJavaMethodHolderName(methodName), interfaceDescriptor, null, null); MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC | Modifier.STATIC, javaMethodName, function.getAsmMethodDescriptorString(), signature, null); List<PythonLikeType> parameterPythonTypeList = function.getParameterTypes(); Type[] javaParameterTypes = new Type[function.totalArgCount()]; for (int i = 0; i < function.totalArgCount(); i++) { javaParameterTypes[i] = Type.getType('L' + parameterPythonTypeList.get(i).getJavaTypeInternalName() + ';'); } createInstanceOrStaticMethodBody(internalClassName, methodName, javaParameterTypes, interfaceDeclaration.methodDescriptor, function, interfaceDeclaration.interfaceName, interfaceDescriptor, methodVisitor); pythonLikeType.addMethod(methodName, new PythonFunctionSignature(new MethodDescriptor(internalClassName, MethodDescriptor.MethodType.STATIC, javaMethodName, function.getAsmMethodDescriptorString()), function.getReturnType().orElse(BuiltinTypes.BASE_TYPE), function.getParameterTypes())); } private static void createClassMethod(PythonLikeType pythonLikeType, ClassWriter classWriter, String internalClassName, String methodName, PythonCompiledFunction function) { InterfaceDeclaration interfaceDeclaration = getInterfaceForClassPythonFunction(function); String interfaceDescriptor = 'L' + interfaceDeclaration.interfaceName + ';'; String javaMethodName = getJavaMethodName(methodName); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, getJavaMethodHolderName(methodName), interfaceDescriptor, null, null); String javaMethodDescriptor = interfaceDeclaration.methodDescriptor; String signature = getFunctionSignature(function, javaMethodDescriptor); MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC | Modifier.STATIC, javaMethodName, javaMethodDescriptor, signature, null); for (int i = 0; i < function.getParameterTypes().size(); i++) { methodVisitor.visitParameter(function.co_varnames.get(i), 0); } addAnnotationsToMethod(function, methodVisitor); methodVisitor.visitCode(); Label start = new Label(); methodVisitor.visitLabel(start); methodVisitor.visitLineNumber(function.getFirstLine(), start); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, internalClassName, getJavaMethodHolderName(methodName), interfaceDescriptor); for (int i = 0; i < function.totalArgCount(); i++) { methodVisitor.visitVarInsn(Opcodes.ALOAD, i); } methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, interfaceDeclaration.interfaceName, "invoke", interfaceDeclaration.methodDescriptor, true); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); List<PythonLikeType> parameterTypes = new ArrayList<>(function.getParameterTypes().size()); parameterTypes.add(BuiltinTypes.TYPE_TYPE); parameterTypes.addAll(function.getParameterTypes().subList(1, function.getParameterTypes().size())); pythonLikeType.addMethod(methodName, new PythonFunctionSignature(new MethodDescriptor(internalClassName, MethodDescriptor.MethodType.CLASS, javaMethodName, interfaceDeclaration.methodDescriptor), function.getReturnType().orElse(BuiltinTypes.BASE_TYPE), parameterTypes)); } private static void createInstanceOrStaticMethodBody(String internalClassName, String methodName, Type[] javaParameterTypes, String methodDescriptorString, PythonCompiledFunction function, String interfaceInternalName, String interfaceDescriptor, MethodVisitor methodVisitor) { for (int i = 0; i < javaParameterTypes.length; i++) { methodVisitor.visitParameter(function.co_varnames.get(i), 0); } addAnnotationsToMethod(function, methodVisitor); methodVisitor.visitCode(); Label start = new Label(); methodVisitor.visitLabel(start); methodVisitor.visitLineNumber(function.getFirstLine(), start); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, internalClassName, getJavaMethodHolderName(methodName), interfaceDescriptor); for (int i = 0; i < function.totalArgCount(); i++) { methodVisitor.visitVarInsn(Opcodes.ALOAD, i); } methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, interfaceInternalName, "invoke", methodDescriptorString, true); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } private static void createOverrideMethod(ClassWriter classWriter, String internalClassName, Method overridenMethod, String overrideMethodDescriptor, Type[] overrideParameterTypes) { var methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, overridenMethod.getName(), Type.getMethodDescriptor(overridenMethod), null, null); methodVisitor.visitAnnotation(Type.getDescriptor(OverrideMethod.class), true).visitEnd(); methodVisitor.visitCode(); if (overridenMethod.getParameterCount() != overrideParameterTypes.length) { methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(NotImplementedError.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(NotImplementedError.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitInsn(Opcodes.ATHROW); } else { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); for (int i = 0; i < overrideParameterTypes.length; i++) { methodVisitor.visitVarInsn(Opcodes.ALOAD, i + 1); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, overrideParameterTypes[i].getInternalName()); } methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, internalClassName, overridenMethod.getName(), overrideMethodDescriptor, false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(overridenMethod.getReturnType())); methodVisitor.visitInsn(Opcodes.ARETURN); } methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } public static Type getVirtualFunctionReturnType(PythonCompiledFunction function) { // Do not determine return type from method body if type annotation absent, // since overrides might return a different type var returnType = function.getReturnType().orElse(BuiltinTypes.BASE_TYPE); return Type.getType(returnType.getJavaTypeDescriptor()); } public static String getFunctionSignature(PythonCompiledFunction function, String asmMethodDescriptor) { var maybeReturnTypeHint = function.getReturnTypeHint(); if (maybeReturnTypeHint.isPresent()) { var returnTypeHint = maybeReturnTypeHint.get(); var signatureWriter = new SignatureWriter(); Type methodType = Type.getMethodType(asmMethodDescriptor); for (int i = 0; i < methodType.getArgumentCount(); i++) { var parameterVisitor = signatureWriter.visitParameterType(); parameterVisitor.visitClassType(methodType.getArgumentTypes()[i].getInternalName()); parameterVisitor.visitEnd(); } visitSignature(returnTypeHint, signatureWriter.visitReturnType()); signatureWriter.visitEnd(); return signatureWriter.toString(); } return null; } public static void createGetAttribute(ClassWriter classWriter, String classInternalName, String superInternalName, Collection<String> instanceAttributes, Map<String, PythonLikeType> fieldToType) { MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), null, null); methodVisitor.visitParameter("attribute", 0); methodVisitor.visitCode(); PythonBytecodeToJavaBytecodeTranslator.visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); BytecodeSwitchImplementor.createStringSwitch(methodVisitor, instanceAttributes, 2, field -> { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); var type = fieldToType.get(field); if (type.getJavaTypeInternalName().equals(Type.getInternalName(JavaObjectWrapper.class))) { methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, getJavaFieldName(field), Type.getDescriptor(type.getJavaObjectWrapperType())); getWrappedJavaObject(methodVisitor); } else { methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, getJavaFieldName(field), 'L' + type.getJavaTypeInternalName() + ';'); } methodVisitor.visitInsn(Opcodes.ARETURN); }, () -> { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superInternalName, "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.ARETURN); }, true); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } private static void getWrappedJavaObject(MethodVisitor methodVisitor) { methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(JavaObjectWrapper.class)); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(JavaObjectWrapper.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object.class)), false); } public static void createSetAttribute(ClassWriter classWriter, String classInternalName, String superInternalName, Collection<String> instanceAttributes, Map<String, PythonLikeType> fieldToType) { MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "$setAttribute", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class), Type.getType(PythonLikeObject.class)), null, null); methodVisitor.visitParameter("attribute", 0); methodVisitor.visitParameter("value", 0); methodVisitor.visitCode(); PythonBytecodeToJavaBytecodeTranslator.visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); BytecodeSwitchImplementor.createStringSwitch(methodVisitor, instanceAttributes, 3, field -> { var type = fieldToType.get(field); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); String typeDescriptor = type.getJavaTypeDescriptor(); if (type.getJavaTypeInternalName().equals(Type.getInternalName(JavaObjectWrapper.class))) { // Need to unwrap the object getUnwrappedJavaObject(methodVisitor, type); typeDescriptor = Type.getDescriptor(type.getJavaObjectWrapperType()); } else { methodVisitor.visitLdcInsn(Type.getType(type.getJavaTypeDescriptor())); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "coerceToType", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(PythonLikeObject.class), Type.getType(Class.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, type.getJavaTypeInternalName()); } methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, getJavaFieldName(field), typeDescriptor); methodVisitor.visitInsn(Opcodes.RETURN); }, () -> { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superInternalName, "$setAttribute", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class), Type.getType(PythonLikeObject.class)), false); methodVisitor.visitInsn(Opcodes.RETURN); }, true); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } private static void getUnwrappedJavaObject(MethodVisitor methodVisitor, PythonLikeType type) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(JavaObjectWrapper.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(JavaObjectWrapper.class), "getWrappedObject", Type.getMethodDescriptor(Type.getType(Object.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getType(type.getJavaObjectWrapperType()).getInternalName()); } public static void createDeleteAttribute(ClassWriter classWriter, String classInternalName, String superInternalName, Collection<String> instanceAttributes, Map<String, PythonLikeType> fieldToType) { MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "$deleteAttribute", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), null, null); methodVisitor.visitParameter("attribute", 0); methodVisitor.visitCode(); PythonBytecodeToJavaBytecodeTranslator.visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); BytecodeSwitchImplementor.createStringSwitch(methodVisitor, instanceAttributes, 2, field -> { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.ACONST_NULL); var fieldType = fieldToType.get(field); if (fieldType.getJavaTypeInternalName().equals(Type.getInternalName(JavaObjectWrapper.class))) { methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, getJavaFieldName(field), Type.getDescriptor(fieldType.getJavaObjectWrapperType())); } else { methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, getJavaFieldName(field), fieldType.getJavaTypeDescriptor()); } methodVisitor.visitInsn(Opcodes.RETURN); }, () -> { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superInternalName, "$deleteAttribute", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.RETURN); }, true); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } public static void createCPythonOperationMethods(ClassWriter classWriter, String internalClassName, String superClassInternalName, Map<String, PythonLikeType> attributeNameToType) { createReadFromCPythonReference(classWriter, internalClassName, superClassInternalName, attributeNameToType); createWriteToCPythonReference(classWriter, internalClassName, superClassInternalName, attributeNameToType); } public static void createReadFromCPythonReference(ClassWriter classWriter, String internalClassName, String superClassInternalName, Map<String, PythonLikeType> attributeNameToType) { MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "$readFieldsFromCPythonReference", Type.getMethodDescriptor(Type.VOID_TYPE), null, null); methodVisitor.visitCode(); PythonBytecodeToJavaBytecodeTranslator.visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClassInternalName, "$readFieldsFromCPythonReference", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(CPythonBackedPythonLikeObject.class), "$cpythonReference", Type.getDescriptor(OpaquePythonReference.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); Label ifReferenceIsNotNull = new Label(); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, ifReferenceIsNotNull); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitLabel(ifReferenceIsNotNull); for (String field : attributeNameToType.keySet()) { methodVisitor.visitInsn(Opcodes.DUP2); methodVisitor.visitLdcInsn(field); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(CPythonBackedPythonLikeObject.class), "$instanceMap", Type.getDescriptor(Map.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(CPythonBackedPythonInterpreter.class), "lookupAttributeOnPythonReference", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(OpaquePythonReference.class), Type.getType(String.class), Type.getType(Map.class)), false); boolean isAssignableFromNone = false; try { isAssignableFromNone = attributeNameToType.get(field).getJavaClass().isAssignableFrom(PythonNone.class); } catch (ClassNotFoundException e) { // do nothing } Label ifFieldIsNone = new Label(); Label doneSettingField = new Label(); if (!isAssignableFromNone) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(PythonNone.class), "INSTANCE", Type.getDescriptor(PythonNone.class)); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, ifFieldIsNone); } var attributeType = attributeNameToType.get(field); methodVisitor.visitLdcInsn(Type.getType(attributeType.getJavaTypeDescriptor())); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "coerceToType", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(PythonLikeObject.class), Type.getType(Class.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, attributeNameToType.get(field).getJavaTypeInternalName()); if (attributeType.getJavaTypeInternalName().equals(Type.getInternalName(JavaObjectWrapper.class))) { Class<?> wrappedJavaType = attributeType.getJavaObjectWrapperType(); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(JavaObjectWrapper.class), "getWrappedObject", Type.getMethodDescriptor(Type.getType(Object.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getType(wrappedJavaType).getInternalName()); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, getJavaFieldName(field), Type.getDescriptor(wrappedJavaType)); } else { methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, getJavaFieldName(field), attributeType.getJavaTypeDescriptor()); } if (!isAssignableFromNone) { methodVisitor.visitJumpInsn(Opcodes.GOTO, doneSettingField); methodVisitor.visitLabel(ifFieldIsNone); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); if (attributeType.getJavaTypeInternalName().equals(Type.getInternalName(JavaObjectWrapper.class))) { methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, getJavaFieldName(field), Type.getDescriptor(attributeType.getJavaObjectWrapperType())); } else { methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, getJavaFieldName(field), attributeType.getJavaTypeDescriptor()); } methodVisitor.visitLabel(doneSettingField); } } methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } public static void createWriteToCPythonReference(ClassWriter classWriter, String internalClassName, String superClassInternalName, Map<String, PythonLikeType> attributeNameToType) { MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "$writeFieldsToCPythonReference", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(OpaquePythonReference.class)), null, null); methodVisitor.visitCode(); PythonBytecodeToJavaBytecodeTranslator.visitGeneratedLineNumber(methodVisitor); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClassInternalName, "$writeFieldsToCPythonReference", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(OpaquePythonReference.class)), false); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(CPythonBackedPythonLikeObject.class), "$cpythonReference", Type.getDescriptor(OpaquePythonReference.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); Label ifReferenceIsNotNull = new Label(); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, ifReferenceIsNotNull); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitLabel(ifReferenceIsNotNull); methodVisitor.visitInsn(Opcodes.SWAP); for (String field : attributeNameToType.keySet()) { methodVisitor.visitInsn(Opcodes.DUP2); var attributeType = attributeNameToType.get(field); if (attributeType.getJavaTypeInternalName().equals(Type.getInternalName(JavaObjectWrapper.class))) { var wrappedJavaType = attributeType.getJavaObjectWrapperType(); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, getJavaFieldName(field), Type.getDescriptor(wrappedJavaType)); methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(JavaObjectWrapper.class)); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(JavaObjectWrapper.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object.class)), false); } else { methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, getJavaFieldName(field), attributeType.getJavaTypeDescriptor()); } methodVisitor.visitLdcInsn(field); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(CPythonBackedPythonInterpreter.class), "setAttributeOnPythonReference", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(OpaquePythonReference.class), Type.getType(OpaquePythonReference.class), Type.getType(String.class), Type.getType(Object.class)), false); } methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } public static InterfaceDeclaration getInterfaceForFunctionSignature(FunctionSignature functionSignature) { return functionSignatureToInterfaceName.computeIfAbsent(functionSignature, PythonClassTranslator::createInterfaceForFunctionSignature); } public static InterfaceDeclaration getInterfaceForPythonFunction(PythonCompiledFunction pythonCompiledFunction) { String[] parameterTypes = new String[pythonCompiledFunction.totalArgCount()]; List<PythonLikeType> parameterTypeAnnotations = pythonCompiledFunction.getParameterTypes(); for (int i = 0; i < parameterTypeAnnotations.size(); i++) { parameterTypes[i] = 'L' + parameterTypeAnnotations.get(i).getJavaTypeInternalName() + ';'; } String returnType = 'L' + pythonCompiledFunction.getReturnType() .orElseGet(() -> getPythonReturnTypeOfFunction(pythonCompiledFunction, false)).getJavaTypeInternalName() + ';'; FunctionSignature functionSignature = new FunctionSignature(returnType, parameterTypes); return functionSignatureToInterfaceName.computeIfAbsent(functionSignature, PythonClassTranslator::createInterfaceForFunctionSignature); } public static InterfaceDeclaration getInterfaceForPythonFunctionIgnoringReturn(PythonCompiledFunction pythonCompiledFunction) { String[] parameterTypes = new String[pythonCompiledFunction.totalArgCount()]; List<PythonLikeType> parameterTypeAnnotations = pythonCompiledFunction.getParameterTypes(); for (int i = 0; i < parameterTypeAnnotations.size(); i++) { var parameterType = parameterTypeAnnotations.get(i); parameterTypes[i] = parameterType.getJavaTypeDescriptor(); } String returnType = pythonCompiledFunction.getReturnType() .orElse(BuiltinTypes.BASE_TYPE).getJavaTypeDescriptor(); FunctionSignature functionSignature = new FunctionSignature(returnType, parameterTypes); return functionSignatureToInterfaceName.computeIfAbsent(functionSignature, PythonClassTranslator::createInterfaceForFunctionSignature); } public static InterfaceDeclaration getInterfaceForInstancePythonFunction(String instanceInternalClassName, PythonCompiledFunction pythonCompiledFunction) { List<PythonLikeType> parameterPythonTypeList = pythonCompiledFunction.getParameterTypes(); String[] pythonParameterTypes = new String[pythonCompiledFunction.totalArgCount()]; if (pythonParameterTypes.length > 0) { pythonParameterTypes[0] = 'L' + instanceInternalClassName + ';'; } return getInterfaceDeclaration(pythonCompiledFunction, parameterPythonTypeList, pythonParameterTypes); } private static PythonClassTranslator.InterfaceDeclaration getInterfaceDeclaration( PythonCompiledFunction pythonCompiledFunction, List<PythonLikeType> parameterPythonTypeList, String[] pythonParameterTypes) { for (int i = 1; i < pythonParameterTypes.length; i++) { pythonParameterTypes[i] = 'L' + parameterPythonTypeList.get(i).getJavaTypeInternalName() + ';'; } String returnType = 'L' + pythonCompiledFunction.getReturnType().map(PythonLikeType::getJavaTypeInternalName) .orElseGet(() -> getPythonReturnTypeOfFunction(pythonCompiledFunction, true).getJavaTypeInternalName()) + ';'; FunctionSignature functionSignature = new FunctionSignature(returnType, pythonParameterTypes); return functionSignatureToInterfaceName.computeIfAbsent(functionSignature, PythonClassTranslator::createInterfaceForFunctionSignature); } public static InterfaceDeclaration getInterfaceForClassPythonFunction(PythonCompiledFunction pythonCompiledFunction) { List<PythonLikeType> parameterPythonTypeList = pythonCompiledFunction.getParameterTypes(); String[] pythonParameterTypes = new String[pythonCompiledFunction.totalArgCount()]; if (pythonParameterTypes.length > 0) { pythonParameterTypes[0] = Type.getDescriptor(PythonLikeType.class); } return getInterfaceDeclaration(pythonCompiledFunction, parameterPythonTypeList, pythonParameterTypes); } public static InterfaceDeclaration createInterfaceForFunctionSignature(FunctionSignature functionSignature) { String maybeClassName = functionSignature.getClassName(); int numberOfInstances = PythonBytecodeToJavaBytecodeTranslator.classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); ClassWriter classWriter = new JavaPythonClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC | Modifier.INTERFACE | Modifier.ABSTRACT, internalClassName, null, Type.getInternalName(Object.class), null); classWriter.visitSource("<generated signature>", null); Type returnType = Type.getType(functionSignature.returnType); Type[] parameterTypes = new Type[functionSignature.parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { parameterTypes[i] = Type.getType(functionSignature.parameterTypes[i]); } classWriter.visitMethod(Modifier.PUBLIC | Modifier.ABSTRACT, "invoke", Type.getMethodDescriptor(returnType, parameterTypes), null, null); classWriter.visitEnd(); PythonBytecodeToJavaBytecodeTranslator.writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); return new InterfaceDeclaration(internalClassName, Type.getMethodDescriptor(returnType, parameterTypes)); } public static Class<?> getInterfaceClassForDeclaration(InterfaceDeclaration interfaceDeclaration) { try { return BuiltinTypes.asmClassLoader.loadClass(interfaceDeclaration.interfaceName.replaceAll("/", ".")); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Cannot load " + interfaceDeclaration.interfaceName + " from the classloader; maybe it was not created?", e); } } private static FlowGraph createFlowGraph(PythonCompiledFunction pythonCompiledFunction, boolean isVirtual) { InterfaceDeclaration interfaceDeclaration = getInterfaceForPythonFunctionIgnoringReturn(pythonCompiledFunction); MethodDescriptor methodDescriptor = new MethodDescriptor(interfaceDeclaration.interfaceName.replace('.', '/'), MethodDescriptor.MethodType.INTERFACE, "invoke", interfaceDeclaration.methodDescriptor); LocalVariableHelper localVariableHelper = new LocalVariableHelper(methodDescriptor.getParameterTypes(), pythonCompiledFunction); List<Opcode> opcodeList = PythonBytecodeToJavaBytecodeTranslator.getOpcodeList(pythonCompiledFunction); StackMetadata initialStackMetadata = PythonBytecodeToJavaBytecodeTranslator.getInitialStackMetadata(localVariableHelper, methodDescriptor, isVirtual); FunctionMetadata functionMetadata = new FunctionMetadata(); functionMetadata.functionType = PythonBytecodeToJavaBytecodeTranslator.getFunctionType(pythonCompiledFunction); functionMetadata.bytecodeCounterToLabelMap = new HashMap<>(); functionMetadata.bytecodeCounterToCodeArgumenterList = new HashMap<>(); functionMetadata.method = methodDescriptor; functionMetadata.pythonCompiledFunction = pythonCompiledFunction; functionMetadata.className = ""; functionMetadata.methodVisitor = null; return FlowGraph.createFlowGraph(functionMetadata, initialStackMetadata, opcodeList); } public static Set<String> getReferencedSelfAttributes(PythonCompiledFunction pythonCompiledFunction) { FlowGraph flowGraph = createFlowGraph(pythonCompiledFunction, true); Set<String> referencedSelfAttributeSet = new HashSet<>(); BiConsumer<AbstractOpcode, StackMetadata> attributeVisitor = (attributeOpcode, stackMetadata) -> { Set<Opcode> possibleSourceOpcodeSet = stackMetadata.getTOSValueSource().getPossibleSourceOpcodeSet(); if (possibleSourceOpcodeSet.stream().anyMatch(opcode -> { if (opcode instanceof LoadFastOpcode || opcode instanceof StoreAttrOpcode || opcode instanceof DeleteAttrOpcode) { AbstractOpcode instructionOpcode = (AbstractOpcode) opcode; return instructionOpcode.getInstruction().arg() == 0; } if (opcode instanceof SelfOpcodeWithoutSource) { return true; } return false; })) { referencedSelfAttributeSet.add(pythonCompiledFunction.co_names.get(attributeOpcode.getInstruction().arg())); } }; flowGraph.visitOperations(LoadAttrOpcode.class, attributeVisitor); flowGraph.visitOperations(StoreAttrOpcode.class, attributeVisitor); flowGraph.visitOperations(DeleteAttrOpcode.class, attributeVisitor); return referencedSelfAttributeSet; } public static PythonLikeType getPythonReturnTypeOfFunction(PythonCompiledFunction pythonCompiledFunction, boolean isVirtual) { try { if (PythonBytecodeToJavaBytecodeTranslator .getFunctionType(pythonCompiledFunction) == PythonFunctionType.GENERATOR) { return BuiltinTypes.GENERATOR_TYPE; } FlowGraph flowGraph = createFlowGraph(pythonCompiledFunction, isVirtual); List<PythonLikeType> possibleReturnTypeList = new ArrayList<>(); flowGraph.visitOperations(ReturnValueOpcode.class, (opcode, stackMetadata) -> { possibleReturnTypeList.add(stackMetadata.getTOSType()); }); flowGraph.visitOperations(ReturnConstantValueOpcode.class, (opcode, stackMetadata) -> { possibleReturnTypeList.add(opcode.getConstant(pythonCompiledFunction).$getGenericType()); }); return possibleReturnTypeList.stream() .reduce(PythonLikeType::unifyWith) .orElse(BuiltinTypes.NONE_TYPE); } catch (UnsupportedOperationException e) { // Return the base type if we encounter any unsupported operations return BuiltinTypes.BASE_TYPE; } catch (Exception e) { System.out.println("WARNING: Ignoring exception"); //System.out.println("globals: " + pythonCompiledFunction.globalsMap); //System.out.println("co_constants: " + pythonCompiledFunction.co_constants); //System.out.println("co_names: " + pythonCompiledFunction.co_names); //System.out.println("co_varnames: " + pythonCompiledFunction.co_varnames); System.out.println("Instructions:"); System.out.println(pythonCompiledFunction.instructionList.stream() .map(PythonBytecodeInstruction::toString) .collect(Collectors.joining("\n"))); e.printStackTrace(); return BuiltinTypes.BASE_TYPE; } } public record InterfaceDeclaration(String interfaceName, String methodDescriptor) { public String descriptor() { return "L" + interfaceName + ";"; } public Type methodType() { return Type.getMethodType(methodDescriptor); } } public static class FunctionSignature { final String returnType; final String[] parameterTypes; public FunctionSignature(String returnType, String... parameterTypes) { this.returnType = returnType; this.parameterTypes = parameterTypes; } public String getClassName() { return PythonBytecodeToJavaBytecodeTranslator.GENERATED_PACKAGE_BASE + "signature.InterfaceSignature"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FunctionSignature that = (FunctionSignature) o; return returnType.equals(that.returnType) && Arrays.equals(parameterTypes, that.parameterTypes); } @Override public int hashCode() { int result = Objects.hash(returnType); result = 31 * result + Arrays.hashCode(parameterTypes); return result; } } public enum PythonMethodKind { VIRTUAL_METHOD, STATIC_METHOD, CLASS_METHOD; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonCompiledClass.java
package ai.timefold.jpyinterpreter; import java.util.List; import java.util.Map; import java.util.Set; import ai.timefold.jpyinterpreter.types.PythonJavaTypeMapping; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.wrappers.CPythonType; import ai.timefold.jpyinterpreter.types.wrappers.OpaquePythonReference; import ai.timefold.jpyinterpreter.util.JavaIdentifierUtils; public class PythonCompiledClass { /** * The module where the class was defined. */ public String module; /** * The path to the file that defines the module. */ public String moduleFilePath; /** * The qualified name of the class. Does not include module. */ public String qualifiedName; public String className; /** * The annotations on the type */ public List<AnnotationMetadata> annotations; /** * Type annotations for fields */ public Map<String, TypeHint> typeAnnotations; /** * Java interfaces the class implement */ public List<Class<?>> javaInterfaces; /** * Mapping from Python types to Java types */ public List<PythonJavaTypeMapping<?, ?>> pythonJavaTypeMappings; /** * The binary type of this PythonCompiledClass; * typically {@link CPythonType}. Used when methods * cannot be generated. */ public PythonLikeType binaryType; public List<PythonLikeType> superclassList; public Map<String, PythonCompiledFunction> instanceFunctionNameToPythonBytecode; public Map<String, PythonCompiledFunction> staticFunctionNameToPythonBytecode; public Map<String, PythonCompiledFunction> classFunctionNameToPythonBytecode; /** * Contains static attributes that are not instances of this class */ public Map<String, PythonLikeObject> staticAttributeNameToObject; /** * Contains static attributes that are instances of this class */ public Map<String, OpaquePythonReference> staticAttributeNameToClassInstance; /** * Contains static attributes that have get/set descriptors */ public Set<String> staticAttributeDescriptorNames; public String getGeneratedClassBaseName() { return getGeneratedClassBaseName(module, qualifiedName); } public static String getGeneratedClassBaseName(String module, String qualifiedName) { if (module == null || module.isEmpty()) { return JavaIdentifierUtils.sanitizeClassName((qualifiedName != null) ? qualifiedName : "PythonClass"); } return JavaIdentifierUtils .sanitizeClassName((qualifiedName != null) ? module + "." + qualifiedName : module + "." + "PythonClass"); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonCompiledFunction.java
package ai.timefold.jpyinterpreter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiFunction; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.util.JavaIdentifierUtils; import ai.timefold.jpyinterpreter.util.arguments.ArgumentSpec; import org.objectweb.asm.Type; public class PythonCompiledFunction { /** * The module where the function was defined. */ public String module; /** * The path to the file that defines the module. */ public String moduleFilePath; /** * The qualified name of the function. Does not include module. */ public String qualifiedName; /** * List of bytecode instructions in the function */ public List<PythonBytecodeInstruction> instructionList; /** * The closure of the function */ public PythonLikeTuple closure; /** * The globals of the function */ public Map<String, PythonLikeObject> globalsMap; /** * Type annotations for the parameters and return. * (return is stored under the "return" key). */ public Map<String, TypeHint> typeAnnotations; /** * Default positional arguments */ public PythonLikeTuple defaultPositionalArguments = new PythonLikeTuple(); /** * Default keyword arguments */ public PythonLikeDict defaultKeywordArguments = new PythonLikeDict(); /** * List of all names used in the function */ public List<String> co_names; /** * List of names used by local variables in the function */ public List<String> co_varnames; /** * List of names used by cell variables */ public List<String> co_cellvars; /** * List of names used by free variables */ public List<String> co_freevars; /** * List of constants used in bytecode */ public List<PythonLikeObject> co_constants; /** * The exception table; only populated in Python 3.11 and above (in Python 3.10 and below, * the table will be empty, since those use explict block instructions) */ public PythonExceptionTable co_exceptiontable; /** * The number of not keyword only arguments the function takes */ public int co_argcount; /** * The number of keyword only arguments the function takes */ public int co_kwonlyargcount; /** * The number of positional only arguments the function takes */ public int co_posonlyargcount; /** * True if the python function can take extra positional arguments that were not specified in its arguments */ public boolean supportExtraPositionalArgs = false; /** * True if the python function can take extra keyword arguments that were not specified in its arguments */ public boolean supportExtraKeywordsArgs = false; /** * The python version this function was compiled in (see sys.hexversion) */ public PythonVersion pythonVersion; public PythonClassTranslator.PythonMethodKind methodKind = PythonClassTranslator.PythonMethodKind.STATIC_METHOD; public PythonCompiledFunction() { } public PythonCompiledFunction copy() { PythonCompiledFunction out = new PythonCompiledFunction(); out.module = module; out.moduleFilePath = moduleFilePath; out.qualifiedName = qualifiedName; out.instructionList = List.copyOf(instructionList); out.closure = closure; out.globalsMap = globalsMap; out.typeAnnotations = typeAnnotations; out.defaultPositionalArguments = defaultPositionalArguments; out.defaultKeywordArguments = defaultKeywordArguments; out.co_exceptiontable = this.co_exceptiontable; out.co_names = List.copyOf(co_names); out.co_varnames = List.copyOf(co_varnames); out.co_cellvars = List.copyOf(co_cellvars); out.co_freevars = List.copyOf(co_freevars); out.co_constants = List.copyOf(co_constants); out.co_argcount = co_argcount; out.co_kwonlyargcount = co_kwonlyargcount; out.pythonVersion = pythonVersion; out.methodKind = methodKind; return out; } public List<PythonLikeType> getParameterTypes() { List<PythonLikeType> out = new ArrayList<>(totalArgCount()); PythonLikeType defaultType = BuiltinTypes.BASE_TYPE; for (int i = 0; i < totalArgCount(); i++) { String parameterName = co_varnames.get(i); var parameterTypeHint = typeAnnotations.get(parameterName); PythonLikeType parameterType = defaultType; if (parameterTypeHint != null) { parameterType = parameterTypeHint.type(); } out.add(parameterType); } return out; } public Optional<PythonLikeType> getReturnType() { var returnTypeHint = typeAnnotations.get("return"); if (returnTypeHint == null) { return Optional.empty(); } return Optional.of(returnTypeHint.type()); } public Optional<TypeHint> getReturnTypeHint() { return Optional.ofNullable(typeAnnotations.get("return")); } public String getAsmMethodDescriptorString() { Type returnType = Type.getType('L' + getReturnType().map(PythonLikeType::getJavaTypeInternalName) .orElseGet(BuiltinTypes.BASE_TYPE::getJavaTypeInternalName) + ';'); List<PythonLikeType> parameterPythonTypeList = getParameterTypes(); Type[] parameterTypes = new Type[totalArgCount()]; for (int i = 0; i < totalArgCount(); i++) { parameterTypes[i] = Type.getType('L' + parameterPythonTypeList.get(i).getJavaTypeInternalName() + ';'); } return Type.getMethodDescriptor(returnType, parameterTypes); } public String getGeneratedClassBaseName() { if (module == null || module.isEmpty()) { return JavaIdentifierUtils.sanitizeClassName((qualifiedName != null) ? qualifiedName : "PythonFunction"); } return JavaIdentifierUtils .sanitizeClassName((qualifiedName != null) ? module + "." + qualifiedName : module + "." + "PythonFunction"); } @SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> Class<T> getParameterJavaClass(List<PythonLikeType> parameterTypeList, int variableIndex) { return (Class) parameterTypeList.get(variableIndex).getJavaClassOrDefault(PythonLikeObject.class); } private static String getParameterJavaClassName(List<PythonLikeType> parameterTypeList, int variableIndex) { return parameterTypeList.get(variableIndex).getJavaTypeInternalName(); } @SuppressWarnings({ "unchecked", "rawtypes" }) public BiFunction<PythonLikeTuple, PythonLikeDict, ArgumentSpec<PythonLikeObject>> getArgumentSpecMapper() { return (defaultPositionalArguments, defaultKeywordArguments) -> { ArgumentSpec<PythonLikeObject> out = ArgumentSpec.forFunctionReturning(qualifiedName, getReturnType() .map(PythonLikeType::getJavaTypeInternalName) .orElse(PythonLikeObject.class.getName())); int variableIndex = 0; int defaultPositionalStartIndex = co_argcount - defaultPositionalArguments.size(); if (methodKind == PythonClassTranslator.PythonMethodKind.VIRTUAL_METHOD) { variableIndex = 1; } List<PythonLikeType> parameterTypeList = getParameterTypes(); for (; variableIndex < co_posonlyargcount; variableIndex++) { if (variableIndex >= defaultPositionalStartIndex) { out = out.addPositionalOnlyArgument(co_varnames.get(variableIndex), getParameterJavaClassName(parameterTypeList, variableIndex), defaultPositionalArguments.get( variableIndex - defaultPositionalStartIndex)); } else { out = out.addPositionalOnlyArgument(co_varnames.get(variableIndex), getParameterJavaClassName(parameterTypeList, variableIndex)); } } for (; variableIndex < co_argcount; variableIndex++) { if (variableIndex >= defaultPositionalStartIndex) { out = out.addArgument(co_varnames.get(variableIndex), getParameterJavaClassName(parameterTypeList, variableIndex), defaultPositionalArguments.get(variableIndex - defaultPositionalStartIndex)); } else { out = out.addArgument(co_varnames.get(variableIndex), getParameterJavaClassName(parameterTypeList, variableIndex)); } } for (int i = 0; i < co_kwonlyargcount; i++) { PythonLikeObject maybeDefault = defaultKeywordArguments.get(PythonString.valueOf(co_varnames.get(variableIndex))); if (maybeDefault != null) { out = out.addKeywordOnlyArgument(co_varnames.get(variableIndex), getParameterJavaClassName(parameterTypeList, variableIndex), maybeDefault); } else { out = out.addKeywordOnlyArgument(co_varnames.get(variableIndex), getParameterJavaClassName(parameterTypeList, variableIndex)); } variableIndex++; } // vargs and kwargs are always last, despite position in signature if (supportExtraPositionalArgs) { out = out.addExtraPositionalVarArgument(co_varnames.get(variableIndex)); variableIndex++; } if (supportExtraKeywordsArgs) { out = out.addExtraKeywordVarArgument(co_varnames.get(variableIndex)); } return out; }; } /** * The total number of arguments the function takes */ public int totalArgCount() { int extraArgs = 0; if (supportExtraPositionalArgs) { extraArgs++; } if (supportExtraKeywordsArgs) { extraArgs++; } return co_argcount + co_kwonlyargcount + extraArgs; } public int getFirstLine() { for (var instruction : instructionList) { if (instruction.startsLine().isPresent()) { return instruction.startsLine().getAsInt(); } } return -1; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonDefaultArgumentImplementor.java
package ai.timefold.jpyinterpreter; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.util.arguments.ArgumentSpec; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implement classes that hold static constants used for default arguments when calling */ public class PythonDefaultArgumentImplementor { public static final String ARGUMENT_PREFIX = "argument_"; public static final String CONSTANT_PREFIX = "DEFAULT_VALUE_"; public static final String ARGUMENT_SPEC_STATIC_FIELD_NAME = "argumentSpec"; public static final String KEY_TUPLE_FIELD_NAME = "keyword_args"; public static final String REMAINING_KEY_ARGUMENTS_FIELD_NAME = "remaining_keys"; public static final String POSITIONAL_INDEX = "positional_index"; public static String getArgumentName(int argumentIndex) { return ARGUMENT_PREFIX + argumentIndex; } public static String getConstantName(int defaultIndex) { return CONSTANT_PREFIX + defaultIndex; } public static String createDefaultArgumentFor(MethodDescriptor methodDescriptor, List<PythonLikeObject> defaultArgumentList, Map<String, Integer> argumentNameToIndexMap, Optional<Integer> extraPositionalArgumentsVariableIndex, Optional<Integer> extraKeywordArgumentsVariableIndex, ArgumentSpec<?> argumentSpec) { String maybeClassName = PythonBytecodeToJavaBytecodeTranslator.GENERATED_PACKAGE_BASE + methodDescriptor.getDeclaringClassInternalName().replace('/', '.') + "." + methodDescriptor.getMethodName() + "$$Defaults"; int numberOfInstances = PythonBytecodeToJavaBytecodeTranslator.classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, internalClassName, null, Type.getInternalName(Object.class), new String[] { Type.getInternalName(PythonLikeFunction.class) }); // static constants classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, ARGUMENT_SPEC_STATIC_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class), null, null); final int defaultStart = methodDescriptor.getParameterTypes().length - defaultArgumentList.size(); for (int i = 0; i < defaultArgumentList.size(); i++) { String fieldName = getConstantName(i); classWriter.visitField(Modifier.PUBLIC | Modifier.STATIC, fieldName, methodDescriptor.getParameterTypes()[defaultStart + i].getDescriptor(), null, null); } // instance fields (representing actual arguments) classWriter.visitField(Modifier.PRIVATE | Modifier.FINAL, KEY_TUPLE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class), null, null); classWriter.visitField(Modifier.PRIVATE, REMAINING_KEY_ARGUMENTS_FIELD_NAME, Type.getDescriptor(int.class), null, null); classWriter.visitField(Modifier.PRIVATE, POSITIONAL_INDEX, Type.getDescriptor(int.class), null, null); for (int i = 0; i < methodDescriptor.getParameterTypes().length; i++) { String fieldName = getArgumentName(i); if (extraPositionalArgumentsVariableIndex.isPresent() && extraPositionalArgumentsVariableIndex.get() == i) { classWriter.visitField(Modifier.PUBLIC, fieldName, Type.getDescriptor(PythonLikeTuple.class), null, null); } else if (extraKeywordArgumentsVariableIndex.isPresent() && extraKeywordArgumentsVariableIndex.get() == i) { classWriter.visitField(Modifier.PUBLIC, fieldName, Type.getDescriptor(PythonLikeDict.class), null, null); } else { classWriter.visitField(Modifier.PUBLIC, fieldName, methodDescriptor.getParameterTypes()[i].getDescriptor(), null, null); } } // public constructor; an instance is created for keyword function calls, since we need consistent stack frames MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeTuple.class), Type.INT_TYPE), null, null); methodVisitor.visitCode(); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, KEY_TUPLE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "size", Type.getMethodDescriptor(Type.INT_TYPE), true); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, REMAINING_KEY_ARGUMENTS_FIELD_NAME, Type.getDescriptor(int.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ILOAD, 2); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, POSITIONAL_INDEX, Type.getDescriptor(int.class)); for (int i = 0; i < defaultArgumentList.size(); i++) { int argumentIndex = i + (methodDescriptor.getParameterTypes().length - defaultArgumentList.size()); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, internalClassName, getConstantName(i), methodDescriptor.getParameterTypes()[defaultStart + i].getDescriptor()); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, getArgumentName(argumentIndex), methodDescriptor.getParameterTypes()[argumentIndex].getDescriptor()); } if (extraPositionalArgumentsVariableIndex.isPresent()) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, getArgumentName(extraPositionalArgumentsVariableIndex.get()), Type.getDescriptor(PythonLikeTuple.class)); } if (extraKeywordArgumentsVariableIndex.isPresent()) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); CollectionImplementor.buildMap(PythonLikeDict.class, methodVisitor, 0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, getArgumentName(extraKeywordArgumentsVariableIndex.get()), Type.getDescriptor(PythonLikeDict.class)); } methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); createAddArgumentMethod(classWriter, internalClassName, methodDescriptor, argumentNameToIndexMap, extraPositionalArgumentsVariableIndex, extraKeywordArgumentsVariableIndex, argumentSpec); // clinit to set ArgumentSpec, as class cannot be loaded if it contains // yet to be compiled forward references methodVisitor = classWriter.visitMethod(Modifier.PUBLIC | Modifier.STATIC, "<clinit>", Type.getMethodDescriptor(Type.VOID_TYPE), null, null); methodVisitor.visitCode(); argumentSpec.loadArgumentSpec(methodVisitor); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.PUTSTATIC, internalClassName, ARGUMENT_SPEC_STATIC_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class)); for (int i = 0; i < defaultArgumentList.size(); i++) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(defaultStart + i); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(ArgumentSpec.class), "getDefaultValue", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getParameterTypes()[defaultStart + i].getInternalName()); String fieldName = getConstantName(i); methodVisitor.visitFieldInsn(Opcodes.PUTSTATIC, internalClassName, fieldName, methodDescriptor.getParameterTypes()[defaultStart + i].getDescriptor()); } methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); classWriter.visitEnd(); PythonBytecodeToJavaBytecodeTranslator.writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); return internalClassName; } /** * Create code that look like this: * * <pre> * void addArgument(PythonLikeObject argument) { * if (remainingKeywords > 0) { * String keyword = keywordTuple.get(remainingKeywords - 1).getValue(); * switch (keyword) { * case "key1": * argument_0 = (Argument0Type) argument; * break; * case "key2": * argument_1 = (Argument1Type) argument; * break; * ... * default: * #ifdef EXTRA_KEYWORD_VAR * EXTRA_KEYWORD_VAR.put(keyword, argument); * #endif * * #ifndef EXTRA_KEYWORD_VAR * throw new TypeError(); * #endif * } * remainingKeywords--; * return; * } else { * switch (positionalIndex) { * case 0: * argument_0 = (Argument0Type) argument; * break; * case 1: * argument_1 = (Argument1Type) argument; * break; * ... * default: * #ifdef EXTRA_POSITIONAL_VAR * EXTRA_POSITIONAL_VAR.add(0, argument); * #endif * * #ifndef EXTRA_POSITIONAL_VAR * throw new TypeError(); * #endif * } * positionalIndex--; * return; * } * } * </pre> * * @param classVisitor * @param classInternalName * @param methodDescriptor * @param argumentNameToIndexMap */ private static void createAddArgumentMethod(ClassVisitor classVisitor, String classInternalName, MethodDescriptor methodDescriptor, Map<String, Integer> argumentNameToIndexMap, Optional<Integer> extraPositionalArgumentsVariableIndex, Optional<Integer> extraKeywordArgumentsVariableIndex, ArgumentSpec<?> argumentSpec) { MethodVisitor methodVisitor = classVisitor.visitMethod(Modifier.PUBLIC, "addArgument", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeObject.class)), null, null); methodVisitor.visitParameter("argument", 0); methodVisitor.visitCode(); Label noMoreKeywordArguments = new Label(); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, REMAINING_KEY_ARGUMENTS_FIELD_NAME, Type.getDescriptor(int.class)); methodVisitor.visitJumpInsn(Opcodes.IFEQ, noMoreKeywordArguments); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, KEY_TUPLE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, REMAINING_KEY_ARGUMENTS_FIELD_NAME, Type.getDescriptor(int.class)); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.ISUB); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonString.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonString.class), "getValue", Type.getMethodDescriptor(Type.getType(String.class)), false); BytecodeSwitchImplementor.createStringSwitch(methodVisitor, argumentNameToIndexMap.keySet(), 2, key -> { int index = argumentNameToIndexMap.get(key); Type parameterType = methodDescriptor.getParameterTypes()[index]; methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, parameterType.getInternalName()); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, getArgumentName(index), parameterType.getDescriptor()); }, () -> { if (extraKeywordArgumentsVariableIndex.isPresent()) { // Extra keys dict methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, getArgumentName(extraKeywordArgumentsVariableIndex.get()), Type.getDescriptor(PythonLikeDict.class)); // Key methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, KEY_TUPLE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, REMAINING_KEY_ARGUMENTS_FIELD_NAME, Type.getDescriptor(int.class)); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.ISUB); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonString.class)); // Value methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonLikeDict.class), "put", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(PythonLikeObject.class), Type.getType(PythonLikeObject.class)), false); methodVisitor.visitInsn(Opcodes.POP); } else { methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(TypeError.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, KEY_TUPLE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, REMAINING_KEY_ARGUMENTS_FIELD_NAME, Type.getDescriptor(int.class)); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.ISUB); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonString.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonString.class), "getValue", Type.getMethodDescriptor(Type.getType(String.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonDefaultArgumentImplementor.class), "getUnknownKeyArgument", Type.getMethodDescriptor(Type.getType(String.class), Type.getType(String.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(TypeError.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.ATHROW); } }, false); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, REMAINING_KEY_ARGUMENTS_FIELD_NAME, Type.getDescriptor(int.class)); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.ISUB); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, REMAINING_KEY_ARGUMENTS_FIELD_NAME, Type.getDescriptor(int.class)); methodVisitor.visitInsn(Opcodes.RETURN); // No more keyword arguments methodVisitor.visitLabel(noMoreKeywordArguments); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, POSITIONAL_INDEX, Type.getDescriptor(int.class)); BytecodeSwitchImplementor.createIntSwitch(methodVisitor, IntStream.range(0, argumentSpec.getAllowPositionalArgumentCount()) .boxed().collect(Collectors.toList()), index -> { Type parameterType = methodDescriptor.getParameterTypes()[index]; methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, parameterType.getInternalName()); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, getArgumentName(index), parameterType.getDescriptor()); }, () -> { if (extraPositionalArgumentsVariableIndex.isPresent()) { // Extra argument tuple methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, getArgumentName(extraPositionalArgumentsVariableIndex.get()), Type.getDescriptor(PythonLikeTuple.class)); // Index (need to insert in front of list since positional arguments are read in reverse) methodVisitor.visitInsn(Opcodes.ICONST_0); // Item methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); // Insert at front of list (since positional arguments are read in reverse) methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonLikeTuple.class), "add", Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE, Type.getType(PythonLikeObject.class)), false); } else { methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(TypeError.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, POSITIONAL_INDEX, Type.getDescriptor(int.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonDefaultArgumentImplementor.class), "getTooManyPositionalArguments", Type.getMethodDescriptor(Type.getType(String.class), Type.INT_TYPE), false); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(TypeError.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.ATHROW); } }, false); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, classInternalName, POSITIONAL_INDEX, Type.getDescriptor(int.class)); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.ISUB); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, classInternalName, POSITIONAL_INDEX, Type.getDescriptor(int.class)); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); } public static String getUnknownKeyArgument(String keyArgument) { return "got an unexpected keyword argument '" + keyArgument + "'"; } public static String getTooManyPositionalArguments(int numOfArguments) { return "Got too many positional arguments (" + numOfArguments + ")"; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonExceptionTable.java
package ai.timefold.jpyinterpreter; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.util.JumpUtils; public class PythonExceptionTable { private final List<ExceptionBlock> blockList; public PythonExceptionTable() { this.blockList = new ArrayList<>(); } public void addEntry(PythonVersion pythonVersion, int blockStartInstructionInclusive, int blockEndInstructionInclusive, int targetByteOffset, int stackDepth, boolean pushLastIndex) { blockList.add( new ExceptionBlock(JumpUtils.getInstructionIndexForByteOffset(blockStartInstructionInclusive, pythonVersion), JumpUtils.getInstructionIndexForByteOffset(blockEndInstructionInclusive, pythonVersion) + 1, JumpUtils.getInstructionIndexForByteOffset(targetByteOffset, pythonVersion), stackDepth, pushLastIndex)); } public List<ExceptionBlock> getEntries() { return blockList; } public boolean containsJumpTarget(int target) { return blockList.stream().anyMatch(block -> block.targetInstruction == target); } public Set<Integer> getJumpTargetSet() { return blockList.stream().map(ExceptionBlock::getTargetInstruction).collect(Collectors.toSet()); } public Set<Integer> getJumpTargetForStartSet(int start) { return blockList.stream() .filter(exceptionBlock -> exceptionBlock.getBlockStartInstructionInclusive() == start) .map(ExceptionBlock::getTargetInstruction) .collect(Collectors.toSet()); } public List<ExceptionBlock> getInnerExceptionBlockList(int start, Set<Integer> possibleJumpTargetSet) { return blockList.stream() .filter(exceptionBlock -> exceptionBlock.getBlockStartInstructionInclusive() == start || exceptionBlock.containsAnyTargetInSet(possibleJumpTargetSet)) .collect(Collectors.toList()); } public Set<Integer> getStartPositionSet() { return blockList.stream().map(ExceptionBlock::getBlockStartInstructionInclusive).collect(Collectors.toSet()); } @Override public String toString() { return blockList.stream().map(ExceptionBlock::toString) .collect(Collectors.joining("\n ", "ExceptionTable:\n ", "")); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PythonExceptionTable that = (PythonExceptionTable) o; return Objects.equals(blockList, that.blockList); } @Override public int hashCode() { return Objects.hash(blockList); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonFunctionSignature.java
package ai.timefold.jpyinterpreter; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.implementors.JavaPythonTypeConversionImplementor; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.util.arguments.ArgumentSpec; import org.objectweb.asm.Type; public class PythonFunctionSignature { private final PythonLikeType returnType; private final PythonLikeType[] parameterTypes; private final MethodDescriptor methodDescriptor; private final List<PythonLikeObject> defaultArgumentList; private final Map<String, Integer> keywordToArgumentIndexMap; private final Optional<Integer> extraPositionalArgumentsVariableIndex; private final Optional<Integer> extraKeywordArgumentsVariableIndex; private final String defaultArgumentHolderClassInternalName; private final ArgumentSpec<?> argumentSpec; private final boolean isFromArgumentSpec; private static Map<String, Integer> extractKeywordArgument(MethodDescriptor methodDescriptor) { Map<String, Integer> out = new HashMap<>(); int index = 0; for (Type parameterType : methodDescriptor.getParameterTypes()) { out.put("arg" + index, index); } return out; } public static PythonFunctionSignature forMethod(Method method) { MethodDescriptor methodDescriptor = new MethodDescriptor(method); PythonLikeType returnType = JavaPythonTypeConversionImplementor.getPythonLikeType(method.getReturnType()); PythonLikeType[] parameterTypes = new PythonLikeType[method.getParameterCount()]; for (int i = 0; i < parameterTypes.length; i++) { parameterTypes[i] = JavaPythonTypeConversionImplementor.getPythonLikeType(method.getParameterTypes()[i]); } return new PythonFunctionSignature(methodDescriptor, returnType, parameterTypes); } public PythonFunctionSignature(MethodDescriptor methodDescriptor, PythonLikeType returnType, PythonLikeType... parameterTypes) { this(methodDescriptor, Collections.emptyList(), extractKeywordArgument(methodDescriptor), returnType, parameterTypes); } public PythonFunctionSignature(MethodDescriptor methodDescriptor, PythonLikeType returnType, List<PythonLikeType> parameterTypeList) { this(methodDescriptor, Collections.emptyList(), extractKeywordArgument(methodDescriptor), returnType, parameterTypeList); } public PythonFunctionSignature(MethodDescriptor methodDescriptor, List<PythonLikeObject> defaultArgumentList, Map<String, Integer> keywordToArgumentIndexMap, PythonLikeType returnType, PythonLikeType... parameterTypes) { this.returnType = returnType; this.parameterTypes = parameterTypes; this.methodDescriptor = methodDescriptor; this.defaultArgumentList = defaultArgumentList; this.keywordToArgumentIndexMap = keywordToArgumentIndexMap; this.extraPositionalArgumentsVariableIndex = Optional.empty(); this.extraKeywordArgumentsVariableIndex = Optional.empty(); isFromArgumentSpec = false; argumentSpec = computeArgumentSpec(); defaultArgumentHolderClassInternalName = PythonDefaultArgumentImplementor.createDefaultArgumentFor(methodDescriptor, defaultArgumentList, keywordToArgumentIndexMap, getExtraPositionalArgumentsVariableIndex(), getExtraKeywordArgumentsVariableIndex(), getArgumentSpec()); } public PythonFunctionSignature(MethodDescriptor methodDescriptor, List<PythonLikeObject> defaultArgumentList, Map<String, Integer> keywordToArgumentIndexMap, PythonLikeType returnType, List<PythonLikeType> parameterTypesList) { this.returnType = returnType; this.parameterTypes = parameterTypesList.toArray(new PythonLikeType[0]); this.methodDescriptor = methodDescriptor; this.defaultArgumentList = defaultArgumentList; this.keywordToArgumentIndexMap = keywordToArgumentIndexMap; this.extraPositionalArgumentsVariableIndex = Optional.empty(); this.extraKeywordArgumentsVariableIndex = Optional.empty(); isFromArgumentSpec = false; argumentSpec = computeArgumentSpec(); defaultArgumentHolderClassInternalName = PythonDefaultArgumentImplementor.createDefaultArgumentFor(methodDescriptor, defaultArgumentList, keywordToArgumentIndexMap, getExtraPositionalArgumentsVariableIndex(), getExtraKeywordArgumentsVariableIndex(), getArgumentSpec()); } public PythonFunctionSignature(MethodDescriptor methodDescriptor, List<PythonLikeObject> defaultArgumentList, Map<String, Integer> keywordToArgumentIndexMap, PythonLikeType returnType, List<PythonLikeType> parameterTypesList, Optional<Integer> extraPositionalArgumentsVariableIndex, Optional<Integer> extraKeywordArgumentsVariableIndex) { this.returnType = returnType; this.parameterTypes = parameterTypesList.toArray(new PythonLikeType[0]); this.methodDescriptor = methodDescriptor; this.defaultArgumentList = defaultArgumentList; this.keywordToArgumentIndexMap = keywordToArgumentIndexMap; this.extraPositionalArgumentsVariableIndex = extraPositionalArgumentsVariableIndex; this.extraKeywordArgumentsVariableIndex = extraKeywordArgumentsVariableIndex; isFromArgumentSpec = false; argumentSpec = computeArgumentSpec(); defaultArgumentHolderClassInternalName = PythonDefaultArgumentImplementor.createDefaultArgumentFor(methodDescriptor, defaultArgumentList, keywordToArgumentIndexMap, extraPositionalArgumentsVariableIndex, extraKeywordArgumentsVariableIndex, getArgumentSpec()); } public PythonFunctionSignature(MethodDescriptor methodDescriptor, List<PythonLikeObject> defaultArgumentList, Map<String, Integer> keywordToArgumentIndexMap, PythonLikeType returnType, List<PythonLikeType> parameterTypesList, Optional<Integer> extraPositionalArgumentsVariableIndex, Optional<Integer> extraKeywordArgumentsVariableIndex, ArgumentSpec<?> argumentSpec) { this.returnType = returnType; this.parameterTypes = parameterTypesList.toArray(new PythonLikeType[0]); this.methodDescriptor = methodDescriptor; this.defaultArgumentList = defaultArgumentList; this.keywordToArgumentIndexMap = keywordToArgumentIndexMap; this.extraPositionalArgumentsVariableIndex = extraPositionalArgumentsVariableIndex; this.extraKeywordArgumentsVariableIndex = extraKeywordArgumentsVariableIndex; this.argumentSpec = argumentSpec; isFromArgumentSpec = true; defaultArgumentHolderClassInternalName = PythonDefaultArgumentImplementor.createDefaultArgumentFor(methodDescriptor, defaultArgumentList, keywordToArgumentIndexMap, extraPositionalArgumentsVariableIndex, extraKeywordArgumentsVariableIndex, argumentSpec); } private ArgumentSpec<?> computeArgumentSpec() { ArgumentSpec<?> argumentSpec = ArgumentSpec.forFunctionReturning(getMethodDescriptor().getMethodName(), getReturnType().getJavaTypeInternalName()); for (int i = 0; i < getParameterTypes().length - getDefaultArgumentList().size(); i++) { if (getExtraPositionalArgumentsVariableIndex().isPresent() && getExtraPositionalArgumentsVariableIndex().get() == i) { continue; } if (getExtraKeywordArgumentsVariableIndex().isPresent() && getExtraKeywordArgumentsVariableIndex().get() == i) { continue; } final int argIndex = i; Optional<String> argumentName = getKeywordToArgumentIndexMap().entrySet() .stream().filter(e -> e.getValue().equals(argIndex)) .map(Map.Entry::getKey) .findAny(); if (argumentName.isEmpty()) { argumentSpec = argumentSpec.addArgument("$arg" + i, getParameterTypes()[i].getJavaTypeInternalName()); } else { argumentSpec = argumentSpec.addArgument(argumentName.get(), getParameterTypes()[i].getJavaTypeInternalName()); } } for (int i = getParameterTypes().length - getDefaultArgumentList().size(); i < getParameterTypes().length; i++) { if (getExtraPositionalArgumentsVariableIndex().isPresent() && getExtraPositionalArgumentsVariableIndex().get() == i) { continue; } if (getExtraKeywordArgumentsVariableIndex().isPresent() && getExtraKeywordArgumentsVariableIndex().get() == i) { continue; } PythonLikeObject defaultValue = getDefaultArgumentList().get(getDefaultArgumentList().size() - (getParameterTypes().length - i)); final int argIndex = i; Optional<String> argumentName = getKeywordToArgumentIndexMap().entrySet() .stream().filter(e -> e.getValue().equals(argIndex)) .map(Map.Entry::getKey) .findAny(); if (argumentName.isEmpty()) { argumentSpec = argumentSpec.addArgument("$arg" + i, getParameterTypes()[i].getJavaTypeInternalName(), defaultValue); } else { argumentSpec = argumentSpec.addArgument(argumentName.get(), getParameterTypes()[i].getJavaTypeInternalName(), defaultValue); } } if (getExtraPositionalArgumentsVariableIndex().isPresent()) { argumentSpec = argumentSpec.addExtraPositionalVarArgument("*vargs"); } if (getExtraKeywordArgumentsVariableIndex().isPresent()) { argumentSpec = argumentSpec.addExtraKeywordVarArgument("**kwargs"); } return argumentSpec; } public ArgumentSpec<?> getArgumentSpec() { return argumentSpec; } public PythonLikeType getReturnType() { return returnType; } public PythonLikeType[] getParameterTypes() { return parameterTypes; } public MethodDescriptor getMethodDescriptor() { return methodDescriptor; } public boolean isFromArgumentSpec() { return isFromArgumentSpec; } public List<PythonLikeObject> getDefaultArgumentList() { return defaultArgumentList; } public Map<String, Integer> getKeywordToArgumentIndexMap() { return keywordToArgumentIndexMap; } public Optional<Integer> getExtraPositionalArgumentsVariableIndex() { return extraPositionalArgumentsVariableIndex; } public Optional<Integer> getExtraKeywordArgumentsVariableIndex() { return extraKeywordArgumentsVariableIndex; } public String getDefaultArgumentHolderClassInternalName() { return defaultArgumentHolderClassInternalName; } public boolean isVirtualMethod() { switch (getMethodDescriptor().getMethodType()) { case VIRTUAL: case INTERFACE: case CONSTRUCTOR: return true; default: return false; } } public boolean isClassMethod() { return getMethodDescriptor().getMethodType() == MethodDescriptor.MethodType.CLASS; } public boolean isStaticMethod() { return getMethodDescriptor().getMethodType() == MethodDescriptor.MethodType.STATIC; } private int getPositionalParameterCount(int originalPositionalParameterCount) { if (getMethodDescriptor().getMethodType() == MethodDescriptor.MethodType.CLASS) { return originalPositionalParameterCount + 1; } else { return originalPositionalParameterCount; } } private List<PythonLikeType> getCallParameterList(List<PythonLikeType> callStackTypeList) { if (getMethodDescriptor().getMethodType() == MethodDescriptor.MethodType.CLASS) { List<PythonLikeType> actualCallParameters = new ArrayList<>(); actualCallParameters.add(BuiltinTypes.TYPE_TYPE); actualCallParameters.addAll(callStackTypeList); return actualCallParameters; } else { return callStackTypeList; } } public boolean matchesParameters(PythonLikeType... callParameters) { return getArgumentSpec().verifyMatchesCallSignature(getPositionalParameterCount(callParameters.length), Collections.emptyList(), getCallParameterList(List.of(callParameters))); } public boolean matchesParameters(int positionalArgumentCount, List<String> keywordArgumentNameList, List<PythonLikeType> callStackTypeList) { return getArgumentSpec().verifyMatchesCallSignature(getPositionalParameterCount(positionalArgumentCount), keywordArgumentNameList, getCallParameterList(callStackTypeList)); } public boolean moreSpecificThan(PythonFunctionSignature other) { if (other.getParameterTypes().length < getParameterTypes().length && (other.getExtraPositionalArgumentsVariableIndex().isPresent() || other.getExtraKeywordArgumentsVariableIndex().isPresent())) { return true; } if (other.getParameterTypes().length > getParameterTypes().length && (getExtraPositionalArgumentsVariableIndex().isPresent() || getExtraKeywordArgumentsVariableIndex().isPresent())) { return false; } if (other.getParameterTypes().length != getParameterTypes().length) { return false; } for (int i = 0; i < getParameterTypes().length; i++) { PythonLikeType overloadParameterType = getParameterTypes()[i]; PythonLikeType otherParameterType = other.getParameterTypes()[i]; if (otherParameterType.equals(overloadParameterType)) { continue; } if (otherParameterType.isSubclassOf(overloadParameterType)) { return false; } } return true; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PythonFunctionSignature that = (PythonFunctionSignature) o; return getReturnType().equals(that.getReturnType()) && Arrays.equals(getParameterTypes(), that.getParameterTypes()) && getExtraPositionalArgumentsVariableIndex().equals(that.getExtraPositionalArgumentsVariableIndex()) && getExtraKeywordArgumentsVariableIndex().equals(that.getExtraKeywordArgumentsVariableIndex()); } @Override public int hashCode() { int result = Objects.hash(getReturnType(), getExtraPositionalArgumentsVariableIndex(), getExtraKeywordArgumentsVariableIndex()); result = 31 * result + Arrays.hashCode(getParameterTypes()); return result; } @Override public String toString() { return getMethodDescriptor().getMethodName() + Arrays.stream(getParameterTypes()).map(PythonLikeType::toString).collect(Collectors.joining(", ", "(", ") -> ")) + getReturnType(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonFunctionType.java
package ai.timefold.jpyinterpreter; public enum PythonFunctionType { /** * A normal function that corresponds to a typical Java Function. */ FUNCTION, /** * A generator function that corresponds to a Java Iterable (has yield opcodes) */ GENERATOR }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonGeneratorTranslator.java
package ai.timefold.jpyinterpreter; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; import ai.timefold.jpyinterpreter.dag.FlowGraph; import ai.timefold.jpyinterpreter.implementors.DunderOperatorImplementor; import ai.timefold.jpyinterpreter.implementors.FunctionImplementor; import ai.timefold.jpyinterpreter.implementors.GeneratorImplementor; import ai.timefold.jpyinterpreter.implementors.PythonConstantsImplementor; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.descriptor.GeneratorOpDescriptor; import ai.timefold.jpyinterpreter.opcodes.generator.GeneratorStartOpcode; import ai.timefold.jpyinterpreter.opcodes.generator.ResumeOpcode; import ai.timefold.jpyinterpreter.opcodes.generator.YieldFromOpcode; import ai.timefold.jpyinterpreter.opcodes.generator.YieldValueOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonCell; import ai.timefold.jpyinterpreter.types.PythonGenerator; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.StopIteration; import ai.timefold.jpyinterpreter.util.JavaPythonClassWriter; import ai.timefold.jpyinterpreter.util.MethodVisitorAdapters; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class PythonGeneratorTranslator { // Needed since value from return is used for StopIteration, meaning to check if a generator has more values // we need to progress it to the next yield/return to determine if it has a next value private static final String SHOULD_PROGRESS_GENERATOR = "$shouldProgressGenerator"; // Remembers where the generator was last yielded at // -1 if the generator hits a return. 0 if generator.__next__() has not been called yet public static final String GENERATOR_STATE = "$generatorState"; // Stack of the generator after it yield a value public static final String GENERATOR_STACK = "$generatorStack"; // The last value yielded by the generator public static final String YIELDED_VALUE = "$yieldedValue"; // The iterator to yield values from, as well as to delegate "send" and "next" calls to public static final String YIELD_FROM_ITERATOR = "$yieldFromIterator"; // The last exception catch by the generator public static final String CURRENT_EXCEPTION = "$currentException"; // The stored stack for an exception handler prefix private static final String EXCEPTION_STACK_PREFIX = "$exceptionHandlerStack"; // Called to advance the generator private static final String PROGRESS_GENERATOR = "progressGenerator"; public static String exceptionHandlerTargetStackLocal(int target) { return EXCEPTION_STACK_PREFIX + target; } public static Class<?> translateGeneratorFunction(PythonCompiledFunction pythonCompiledFunction) { String maybeClassName = PythonBytecodeToJavaBytecodeTranslator.USER_PACKAGE_BASE + pythonCompiledFunction.getGeneratedClassBaseName() + "$Generator"; int numberOfInstances = PythonBytecodeToJavaBytecodeTranslator.classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); ClassWriter classWriter = new JavaPythonClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, internalClassName, null, Type.getInternalName(PythonGenerator.class), null); // Create fields for generator state classWriter.visitField(Modifier.PRIVATE, SHOULD_PROGRESS_GENERATOR, Type.BOOLEAN_TYPE.getDescriptor(), null, null); classWriter.visitField(Modifier.PRIVATE, GENERATOR_STATE, Type.INT_TYPE.getDescriptor(), null, null); classWriter.visitField(Modifier.PRIVATE, GENERATOR_STACK, Type.getDescriptor(List.class), null, null); classWriter.visitField(Modifier.PRIVATE, YIELDED_VALUE, Type.getDescriptor(PythonLikeObject.class), null, null); classWriter.visitField(Modifier.PRIVATE, YIELD_FROM_ITERATOR, Type.getDescriptor(PythonLikeObject.class), null, null); classWriter.visitField(Modifier.PRIVATE, CURRENT_EXCEPTION, Type.getDescriptor(Throwable.class), null, null); // Create fields for translated functions PythonBytecodeToJavaBytecodeTranslator.createFields(classWriter); // Create fields for parameters, cells and local variables { // Cannot use parameter types as the type descriptor, since the variables assigned to the // Python parameter can change types in the middle of code for (int variable = 0; variable < pythonCompiledFunction.co_varnames.size(); variable++) { classWriter.visitField(Modifier.PRIVATE, pythonCompiledFunction.co_varnames.get(variable), Type.getDescriptor(PythonLikeObject.class), null, null); } for (int i = 0; i < pythonCompiledFunction.co_cellvars.size(); i++) { classWriter.visitField(Modifier.PRIVATE, pythonCompiledFunction.co_cellvars.get(i), Type.getDescriptor(PythonCell.class), null, null); } for (int i = 0; i < pythonCompiledFunction.co_freevars.size(); i++) { classWriter.visitField(Modifier.PRIVATE, pythonCompiledFunction.co_freevars.get(i), Type.getDescriptor(PythonCell.class), null, null); } for (int target : pythonCompiledFunction.co_exceptiontable.getJumpTargetSet()) { classWriter.visitField(Modifier.PRIVATE, exceptionHandlerTargetStackLocal(target), Type.getDescriptor(PythonLikeObject[].class), null, null); } } Type[] javaParameterTypes = Stream.concat(Stream.of(Type.getType(PythonLikeTuple.class), Type.getType(PythonLikeDict.class), Type.getType(PythonLikeDict.class), Type.getType(PythonLikeTuple.class), Type.getType(PythonString.class), Type.getType(PythonInterpreter.class)), pythonCompiledFunction.getParameterTypes().stream() .map(type -> Type.getType(type.getJavaTypeDescriptor()))) .toArray(Type[]::new); // Create constructor that sets parameters and initial generator state MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, javaParameterTypes), null, null); methodVisitor.visitCode(); // Call super methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonGenerator.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); // Positional only and Positional/Keyword default arguments methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, PythonBytecodeToJavaBytecodeTranslator.DEFAULT_POSITIONAL_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); // Keyword only default arguments methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, PythonBytecodeToJavaBytecodeTranslator.DEFAULT_KEYWORD_ARGS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); // Annotation Directory as key/value tuple methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 3); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, PythonBytecodeToJavaBytecodeTranslator.ANNOTATION_DIRECTORY_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeDict.class)); // Free variable cells methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 4); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, PythonBytecodeToJavaBytecodeTranslator.CELLS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); // Function name methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 5); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, PythonBytecodeToJavaBytecodeTranslator.QUALIFIED_NAME_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonString.class)); // Interpreter methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 6); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, PythonBytecodeToJavaBytecodeTranslator.INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); // Set initial generator state methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(true); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, SHOULD_PROGRESS_GENERATOR, Type.BOOLEAN_TYPE.getDescriptor()); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, GENERATOR_STATE, Type.INT_TYPE.getDescriptor()); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, GENERATOR_STACK, Type.getDescriptor(List.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, YIELDED_VALUE, Type.getDescriptor(PythonLikeObject.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, YIELD_FROM_ITERATOR, Type.getDescriptor(PythonLikeObject.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, CURRENT_EXCEPTION, Type.getDescriptor(Throwable.class)); // Set parameters { for (int parameter = 0; parameter < pythonCompiledFunction.getParameterTypes().size(); parameter++) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, parameter + 7); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, pythonCompiledFunction.co_varnames.get(parameter), Type.getDescriptor(PythonLikeObject.class)); } } GeneratorLocalVariableHelper localVariableHelper = new GeneratorLocalVariableHelper(classWriter, internalClassName, new Type[] {}, pythonCompiledFunction); localVariableHelper.resetCallKeywords(methodVisitor); // Load cells for (int i = 0; i < localVariableHelper.getNumberOfBoundCells(); i++) { VariableImplementor.createCell(methodVisitor, localVariableHelper, i); } for (int i = 0; i < localVariableHelper.getNumberOfFreeCells(); i++) { VariableImplementor.setupFreeVariableCell(methodVisitor, internalClassName, localVariableHelper, i); } methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); generateHasNext(classWriter, internalClassName, pythonCompiledFunction); generateNext(classWriter, internalClassName, pythonCompiledFunction); Map<Integer, GeneratorMethodPart> generatorStateToMethodPart = createGeneratorStateToMethod(classWriter, internalClassName, pythonCompiledFunction); generateProgressGenerator(classWriter, internalClassName, generatorStateToMethodPart); generateAdvanceGeneratorMethods(classWriter, internalClassName, generatorStateToMethodPart); classWriter.visitEnd(); PythonBytecodeToJavaBytecodeTranslator.writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); try { Class<?> out = BuiltinTypes.asmClassLoader.loadClass(className); PythonBytecodeToJavaBytecodeTranslator.setStaticFields(out, pythonCompiledFunction); return out; } catch (ClassNotFoundException e) { throw new IllegalStateException("Cannot load class " + className + " despite it being just generated.", e); } } private static void generateHasNext(ClassWriter classWriter, String internalClassName, PythonCompiledFunction pythonCompiledFunction) { MethodVisitor methodVisitor = MethodVisitorAdapters .adapt(classWriter.visitMethod(Modifier.PUBLIC, "hasNext", Type.getMethodDescriptor(Type.BOOLEAN_TYPE), null, null), "hasNext", Type.getMethodDescriptor(Type.BOOLEAN_TYPE)); methodVisitor.visitCode(); Label checkIfGeneratorEnded = new Label(); // Check if we need to progress generator methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, SHOULD_PROGRESS_GENERATOR, Type.BOOLEAN_TYPE.getDescriptor()); methodVisitor.visitJumpInsn(Opcodes.IFEQ, checkIfGeneratorEnded); // We need to progress generator methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, internalClassName, PROGRESS_GENERATOR, Type.getMethodDescriptor(Type.VOID_TYPE), false); // generator been progressed, so future hasNext calls (until next is called) should not progress generator methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, SHOULD_PROGRESS_GENERATOR, Type.BOOLEAN_TYPE.getDescriptor()); methodVisitor.visitLabel(checkIfGeneratorEnded); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, GENERATOR_STATE, Type.INT_TYPE.getDescriptor()); methodVisitor.visitLdcInsn(-1); Label generatorEnded = new Label(); methodVisitor.visitJumpInsn(Opcodes.IF_ICMPEQ, generatorEnded); // generator state is not -1, so there are more values methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.IRETURN); methodVisitor.visitLabel(generatorEnded); // generator state is -1, so there are no more values methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitInsn(Opcodes.IRETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } private static void generateNext(ClassWriter classWriter, String internalClassName, PythonCompiledFunction pythonCompiledFunction) { MethodVisitor methodVisitor = MethodVisitorAdapters .adapt(classWriter.visitMethod(Modifier.PUBLIC, "next", Type.getMethodDescriptor(Type.getType(Object.class)), null, null), "next", Type.getMethodDescriptor(Type.getType(Object.class))); methodVisitor.visitCode(); Label returnYieldedValue = new Label(); // Check if we need to progress generator methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, SHOULD_PROGRESS_GENERATOR, Type.BOOLEAN_TYPE.getDescriptor()); methodVisitor.visitJumpInsn(Opcodes.IFEQ, returnYieldedValue); // We need to progress generator methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, internalClassName, PROGRESS_GENERATOR, Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitLabel(returnYieldedValue); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, GENERATOR_STATE, Type.INT_TYPE.getDescriptor()); methodVisitor.visitLdcInsn(-1); Label generatorEnded = new Label(); methodVisitor.visitJumpInsn(Opcodes.IF_ICMPEQ, generatorEnded); // generator state is not -1, so there are more values methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); // next call should progress generator methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, SHOULD_PROGRESS_GENERATOR, Type.BOOLEAN_TYPE.getDescriptor()); // get the yielded value and return it methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, YIELDED_VALUE, Type.getDescriptor(PythonLikeObject.class)); methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitLabel(generatorEnded); // generator state is -1, so there are no more values methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); // next call should not progress generator, since it ended methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, SHOULD_PROGRESS_GENERATOR, Type.BOOLEAN_TYPE.getDescriptor()); // We need to throw StopIteration with the return value, which is stored in YIELDED_VALUE methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, YIELDED_VALUE, Type.getDescriptor(PythonLikeObject.class)); methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(StopIteration.class)); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(StopIteration.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeObject.class)), false); methodVisitor.visitInsn(Opcodes.ATHROW); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } private static void generateProgressGenerator(ClassWriter classWriter, String internalClassName, Map<Integer, GeneratorMethodPart> generatorStateToMethodPartMap) { MethodVisitor methodVisitor = MethodVisitorAdapters .adapt(classWriter.visitMethod(Modifier.PRIVATE, PROGRESS_GENERATOR, Type.getMethodDescriptor(Type.VOID_TYPE), null, null), PROGRESS_GENERATOR, Type.getMethodDescriptor(Type.VOID_TYPE)); methodVisitor.visitCode(); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, GENERATOR_STATE, Type.INT_TYPE.getDescriptor()); BytecodeSwitchImplementor.createIntSwitch(methodVisitor, generatorStateToMethodPartMap.keySet(), generatorState -> { GeneratorMethodPart generatorMethodPart = generatorStateToMethodPartMap.get(generatorState); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); generatorMethodPart.functionMetadata.method.callMethod(methodVisitor); }, () -> { }, false); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } private static void generateAdvanceGeneratorMethods(ClassWriter classWriter, String internalClassName, Map<Integer, GeneratorMethodPart> generatorStateToMethodPartMap) { generatorStateToMethodPartMap.values().forEach( generatorMethodPart -> generateAdvanceGeneratorMethod(classWriter, internalClassName, generatorMethodPart)); } private static void generateAdvanceGeneratorMethod(ClassWriter classWriter, String internalClassName, GeneratorMethodPart generatorMethodPart) { var instruction = AbstractOpcode.lookupInstruction(generatorMethodPart.instruction.opname()); if (!(instruction instanceof GeneratorOpDescriptor generatorInstruction)) { throw new IllegalArgumentException( "Invalid opcode for instruction: %s".formatted(generatorMethodPart.instruction.opname())); } switch (generatorInstruction) { case YIELD_VALUE -> generateAdvanceGeneratorMethodForYieldValue(classWriter, internalClassName, generatorMethodPart); case YIELD_FROM -> generateAdvanceGeneratorMethodForYieldFrom(classWriter, internalClassName, generatorMethodPart); default -> throw new IllegalArgumentException( "Invalid opcode for instruction: " + generatorMethodPart.instruction.opname()); } } private static void generateAdvanceGeneratorMethodForYieldValue(ClassWriter classWriter, String internalClassName, GeneratorMethodPart generatorMethodPart) { MethodVisitor methodVisitor = generatorMethodPart.functionMetadata.methodVisitor; List<Opcode> opcodeList = PythonBytecodeToJavaBytecodeTranslator .getOpcodeList(generatorMethodPart.functionMetadata.pythonCompiledFunction); // First, restore stack methodVisitor.visitCode(); GeneratorImplementor.restoreGeneratorState(generatorMethodPart.functionMetadata, generatorMethodPart.initialStackMetadata); if (generatorMethodPart.afterYield != 0 || (opcodeList.size() > 0 && opcodeList.get(0) instanceof GeneratorStartOpcode)) { // Push the sent value to the stack methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(PythonGenerator.class), "sentValue", Type.getDescriptor(PythonLikeObject.class)); // Set the sent value to None methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); PythonConstantsImplementor.loadNone(methodVisitor); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, Type.getInternalName(PythonGenerator.class), "sentValue", Type.getDescriptor(PythonLikeObject.class)); } // Now generate bytecode for method StackMetadata initialStackMetadata = PythonBytecodeToJavaBytecodeTranslator.getInitialStackMetadata( generatorMethodPart.initialStackMetadata.localVariableHelper, generatorMethodPart.originalMethodDescriptor, false); FlowGraph flowGraph = FlowGraph.createFlowGraph(generatorMethodPart.functionMetadata, initialStackMetadata, opcodeList); List<StackMetadata> stackMetadataForOpcodeIndex = flowGraph.getStackMetadataForOperations(); initialStackMetadata.localVariableHelper.resetCallKeywords(methodVisitor); if (generatorMethodPart.afterYield != 0) { Label afterYieldLabel = new Label(); generatorMethodPart.functionMetadata.bytecodeCounterToLabelMap.put(generatorMethodPart.afterYield, afterYieldLabel); methodVisitor.visitJumpInsn(Opcodes.GOTO, afterYieldLabel); } ResumeOpcode.ResumeType resumeType = ResumeOpcode.ResumeType.YIELD; if (opcodeList.get(generatorMethodPart.afterYield) instanceof ResumeOpcode) { resumeType = ((ResumeOpcode) opcodeList.get(generatorMethodPart.afterYield)).getResumeType(); } final ResumeOpcode.ResumeType actualResumeType = resumeType; PythonBytecodeToJavaBytecodeTranslator.writeInstructionsForOpcodes(generatorMethodPart.functionMetadata, stackMetadataForOpcodeIndex, opcodeList, instruction -> { if (actualResumeType == ResumeOpcode.ResumeType.YIELD) { if (instruction.offset() == generatorMethodPart.afterYield) { // Put thrownValue on TOS methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(PythonGenerator.class), "thrownValue", Type.getDescriptor(Throwable.class)); // Set thrownValue to null methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, Type.getInternalName(PythonGenerator.class), "thrownValue", Type.getDescriptor(Throwable.class)); // Duplicate top methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); Label doNotThrowException = new Label(); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, doNotThrowException); // If thrownValue is null, continue // else, raise thrownValue methodVisitor.visitInsn(Opcodes.ATHROW); methodVisitor.visitLabel(doNotThrowException); // continue as normal methodVisitor.visitInsn(Opcodes.POP); // Pop top, since it was not an exception } } else { switch (actualResumeType) { case YIELD_FROM: case AWAIT: break; default: throw new IllegalArgumentException( "Invalid resume type after YIELD_VALUE: " + actualResumeType); } } }); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } private static void generateAdvanceGeneratorMethodForYieldFrom(ClassWriter classWriter, String internalClassName, GeneratorMethodPart generatorMethodPart) { MethodVisitor methodVisitor = generatorMethodPart.functionMetadata.methodVisitor; methodVisitor.visitCode(); // Generate bytecode for method StackMetadata initialStackMetadata = PythonBytecodeToJavaBytecodeTranslator.getInitialStackMetadata( generatorMethodPart.initialStackMetadata.localVariableHelper, generatorMethodPart.originalMethodDescriptor, false); List<Opcode> opcodeList = PythonBytecodeToJavaBytecodeTranslator .getOpcodeList(generatorMethodPart.functionMetadata.pythonCompiledFunction); FlowGraph flowGraph = FlowGraph.createFlowGraph(generatorMethodPart.functionMetadata, initialStackMetadata, opcodeList); List<StackMetadata> stackMetadataForOpcodeIndex = flowGraph.getStackMetadataForOperations(); initialStackMetadata.localVariableHelper.resetCallKeywords(methodVisitor); if (generatorMethodPart.afterYield != 0) { Label afterYieldLabel = new Label(); generatorMethodPart.functionMetadata.bytecodeCounterToLabelMap.put(generatorMethodPart.afterYield, afterYieldLabel); methodVisitor.visitJumpInsn(Opcodes.GOTO, afterYieldLabel); } PythonBytecodeToJavaBytecodeTranslator.writeInstructionsForOpcodes(generatorMethodPart.functionMetadata, stackMetadataForOpcodeIndex, opcodeList, instruction -> { if (instruction.offset() == generatorMethodPart.afterYield) { // 0 = next, 1 = send, 2 = throw Label wasNotSentValue = new Label(); Label wasNotThrownValue = new Label(); Label iterateSubiterator = new Label(); // Push subiterator methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, YIELD_FROM_ITERATOR, Type.getDescriptor(PythonLikeObject.class)); // Check if sent a value methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(PythonGenerator.class), "sentValue", Type.getDescriptor(PythonLikeObject.class)); PythonConstantsImplementor.loadNone(methodVisitor); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, wasNotSentValue); methodVisitor.visitLdcInsn(1); methodVisitor.visitJumpInsn(Opcodes.GOTO, iterateSubiterator); methodVisitor.visitLabel(wasNotSentValue); // Check if thrown a value methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(PythonGenerator.class), "thrownValue", Type.getDescriptor(Throwable.class)); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, wasNotThrownValue); methodVisitor.visitLdcInsn(2); methodVisitor.visitJumpInsn(Opcodes.GOTO, iterateSubiterator); methodVisitor.visitLabel(wasNotThrownValue); methodVisitor.visitLdcInsn(0); methodVisitor.visitLabel(iterateSubiterator); Label tryStartLabel = new Label(); Label tryEndLabel = new Label(); Label catchStartLabel = new Label(); Label catchEndLabel = new Label(); methodVisitor.visitTryCatchBlock(tryStartLabel, tryEndLabel, catchStartLabel, Type.getInternalName(StopIteration.class)); methodVisitor.visitLabel(tryStartLabel); BytecodeSwitchImplementor.createIntSwitch(methodVisitor, List.of(0, 1, 2), key -> { Label generatorOperationDone = new Label(); switch (key) { case 0: { // next DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.NEXT); break; } case 1: { // send methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(PythonGenerator.class), "sentValue", Type.getDescriptor(PythonLikeObject.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); PythonConstantsImplementor.loadNone(methodVisitor); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, Type.getInternalName(PythonGenerator.class), "sentValue", Type.getDescriptor(PythonLikeObject.class)); FunctionImplementor.callBinaryMethod(methodVisitor, PythonBinaryOperator.SEND.dunderMethod); break; } case 2: { // throw methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(PythonGenerator.class), "thrownValue", Type.getDescriptor(Throwable.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, Type.getInternalName(PythonGenerator.class), "thrownValue", Type.getDescriptor(Throwable.class)); methodVisitor.visitInsn(Opcodes.SWAP); // Stack is now Throwable, Generator // Check if the subgenerator has a "throw" method methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn("throw"); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); // Stack is now Throwable, Generator, maybeMethod Label ifThrowMethodPresent = new Label(); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, ifThrowMethodPresent); // does not have a throw method // Set yieldFromIterator to null since it is finished methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, PythonGeneratorTranslator.YIELD_FROM_ITERATOR, Type.getDescriptor(PythonLikeObject.class)); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.ATHROW); methodVisitor.visitLabel(ifThrowMethodPresent); // Swap so it Generator, Throwable instead of Throwable, Generator methodVisitor.visitInsn(Opcodes.SWAP); FunctionImplementor.callBinaryMethod(methodVisitor, PythonBinaryOperator.THROW.dunderMethod); break; } } methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeObject.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, PythonGeneratorTranslator.YIELDED_VALUE, Type.getDescriptor(PythonLikeObject.class)); methodVisitor.visitInsn(Opcodes.RETURN); // subiterator yielded something; return control to caller }, () -> { methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalStateException.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalStateException.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitInsn(Opcodes.ATHROW); }, true); methodVisitor.visitLabel(tryEndLabel); methodVisitor.visitLabel(catchStartLabel); methodVisitor.visitInsn(Opcodes.POP); // pop the StopIteration exception methodVisitor.visitLabel(catchEndLabel); // Set yieldFromIterator to null since it is finished methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, PythonGeneratorTranslator.YIELD_FROM_ITERATOR, Type.getDescriptor(PythonLikeObject.class)); // Restore the stack GeneratorImplementor.restoreGeneratorState(generatorMethodPart.functionMetadata, generatorMethodPart.initialStackMetadata); // Push the last yielded value to TOS methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, PythonGeneratorTranslator.YIELDED_VALUE, Type.getDescriptor(PythonLikeObject.class)); // Set yielded value to null methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, internalClassName, PythonGeneratorTranslator.YIELDED_VALUE, Type.getDescriptor(PythonLikeObject.class)); // Resume execution } }); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } private static Map<Integer, GeneratorMethodPart> createGeneratorStateToMethod(ClassWriter classWriter, String internalClassName, PythonCompiledFunction pythonCompiledFunction) { Map<Integer, GeneratorMethodPart> generatorStateToMethod = new HashMap<>(); MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PRIVATE, "advance", Type.getMethodDescriptor(Type.VOID_TYPE), null, null); methodVisitor = MethodVisitorAdapters.adapt(methodVisitor, "advance", Type.getMethodDescriptor(Type.VOID_TYPE)); Map<Integer, List<Runnable>> bytecodeIndexToArgumentorsMap = new HashMap<>(); Map<Integer, Label> bytecodeCounterToLabelMap = new HashMap<>(); FunctionMetadata functionMetadata = new FunctionMetadata(); functionMetadata.functionType = PythonFunctionType.GENERATOR; functionMetadata.method = new MethodDescriptor(internalClassName, MethodDescriptor.MethodType.VIRTUAL, "advance", Type.getMethodDescriptor(Type.VOID_TYPE)); functionMetadata.bytecodeCounterToCodeArgumenterList = bytecodeIndexToArgumentorsMap; functionMetadata.bytecodeCounterToLabelMap = bytecodeCounterToLabelMap; functionMetadata.methodVisitor = methodVisitor; functionMetadata.pythonCompiledFunction = pythonCompiledFunction; functionMetadata.className = internalClassName; GeneratorLocalVariableHelper localVariableHelper = new GeneratorLocalVariableHelper(classWriter, internalClassName, new Type[] {}, pythonCompiledFunction); MethodDescriptor stackMetadataMethod = new MethodDescriptor(internalClassName, MethodDescriptor.MethodType.STATIC, pythonCompiledFunction.qualifiedName, pythonCompiledFunction.getAsmMethodDescriptorString()); StackMetadata initialStackMetadata = PythonBytecodeToJavaBytecodeTranslator.getInitialStackMetadata(localVariableHelper, stackMetadataMethod, false); List<Opcode> opcodeList = PythonBytecodeToJavaBytecodeTranslator.getOpcodeList(pythonCompiledFunction); FlowGraph flowGraph = FlowGraph.createFlowGraph(functionMetadata, initialStackMetadata, opcodeList); flowGraph.visitOperations(YieldValueOpcode.class, (yieldValueOpcode, priorStackMetadata) -> { generatorStateToMethod.put(yieldValueOpcode.getBytecodeIndex() + 1, getGeneratorMethodPartForYield(internalClassName, classWriter, pythonCompiledFunction, stackMetadataMethod, priorStackMetadata.pop(), yieldValueOpcode)); }); flowGraph.visitOperations(YieldFromOpcode.class, (yieldFromOpcode, priorStackMetadata) -> { generatorStateToMethod.put(yieldFromOpcode.getBytecodeIndex() + 1, getGeneratorMethodPartForYield(internalClassName, classWriter, pythonCompiledFunction, stackMetadataMethod, priorStackMetadata.pop(2), yieldFromOpcode)); }); GeneratorMethodPart start = new GeneratorMethodPart(); start.initialStackMetadata = initialStackMetadata; start.functionMetadata = functionMetadata; start.afterYield = 0; start.originalMethodDescriptor = stackMetadataMethod; start.instruction = PythonBytecodeInstruction.atOffset(GeneratorOpDescriptor.YIELD_VALUE, 0); generatorStateToMethod.put(0, start); return generatorStateToMethod; } private static GeneratorMethodPart getGeneratorMethodPartForYield(String internalClassName, ClassWriter classWriter, PythonCompiledFunction pythonCompiledFunction, MethodDescriptor originalMethodDescriptor, StackMetadata stackMetadata, AbstractOpcode opcode) { final String methodName = "advance" + (opcode.getBytecodeIndex() + 1); GeneratorMethodPart out = new GeneratorMethodPart(); out.initialStackMetadata = stackMetadata; out.afterYield = opcode.getBytecodeIndex() + 1; out.instruction = opcode.getInstruction(); out.originalMethodDescriptor = originalMethodDescriptor; FunctionMetadata functionMetadata = new FunctionMetadata(); out.functionMetadata = functionMetadata; functionMetadata.functionType = PythonFunctionType.GENERATOR; functionMetadata.method = new MethodDescriptor(internalClassName, MethodDescriptor.MethodType.VIRTUAL, methodName, Type.getMethodDescriptor(Type.VOID_TYPE)); functionMetadata.bytecodeCounterToLabelMap = new HashMap<>(); functionMetadata.bytecodeCounterToCodeArgumenterList = new HashMap<>(); functionMetadata.className = internalClassName; functionMetadata.methodVisitor = classWriter.visitMethod(Modifier.PRIVATE, methodName, Type.getMethodDescriptor(Type.VOID_TYPE), null, null); functionMetadata.methodVisitor = MethodVisitorAdapters.adapt(functionMetadata.methodVisitor, methodName, Type.getMethodDescriptor(Type.VOID_TYPE)); functionMetadata.pythonCompiledFunction = pythonCompiledFunction.copy(); return out; } private static class GeneratorMethodPart { FunctionMetadata functionMetadata; StackMetadata initialStackMetadata; MethodDescriptor originalMethodDescriptor; int afterYield; PythonBytecodeInstruction instruction; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonInterpreter.java
package ai.timefold.jpyinterpreter; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.PythonTraceback; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.jpyinterpreter.types.wrappers.OpaquePythonReference; public interface PythonInterpreter { PythonInterpreter DEFAULT = new CPythonBackedPythonInterpreter(); boolean hasValidPythonReference(PythonLikeObject instance); void setPythonReference(PythonLikeObject instance, OpaquePythonReference reference); PythonLikeObject getGlobal(Map<String, PythonLikeObject> globalsMap, String name); void setGlobal(Map<String, PythonLikeObject> globalsMap, String name, PythonLikeObject value); void deleteGlobal(Map<String, PythonLikeObject> globalsMap, String name); PythonLikeObject importModule(PythonInteger level, List<PythonString> fromList, Map<String, PythonLikeObject> globalsMap, Map<String, PythonLikeObject> localsMap, String moduleName); /** * Writes output without a trailing newline to standard output * * @param output the text to write */ void write(String output); /** * Reads a line from standard input * * @return A line read from standard input */ String readLine(); PythonTraceback getTraceback(); }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonLikeObject.java
package ai.timefold.jpyinterpreter; import java.util.Objects; import ai.timefold.jpyinterpreter.builtins.TernaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.CPythonBackedPythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.AttributeError; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; /** * Represents an Object that can be interacted with like a Python Object. * A PythonLikeObject can refer to a Java Object, a CPython Object, or * be an Object constructed by the Java Python Interpreter. */ public interface PythonLikeObject { /** * Gets an attribute by name. * * @param attributeName Name of the attribute to get * @return The attribute of the object that corresponds with attributeName * @throws AttributeError if the attribute does not exist */ PythonLikeObject $getAttributeOrNull(String attributeName); /** * Gets an attribute by name. * * @param attributeName Name of the attribute to get * @return The attribute of the object that corresponds with attributeName * @throws AttributeError if the attribute does not exist */ default PythonLikeObject $getAttributeOrError(String attributeName) { PythonLikeObject out = this.$getAttributeOrNull(attributeName); if (out == null) { throw new AttributeError("object '" + this + "' does not have attribute '" + attributeName + "'"); } return out; } /** * Sets an attribute by name. * * @param attributeName Name of the attribute to set * @param value Value to set the attribute to */ void $setAttribute(String attributeName, PythonLikeObject value); /** * Delete an attribute by name. * * @param attributeName Name of the attribute to delete */ void $deleteAttribute(String attributeName); /** * Returns the type describing the object * * @return the type describing the object */ PythonLikeType $getType(); /** * Return a generic version of {@link PythonLikeObject#$getType()}. This is used in bytecode * generation and not at runtime. For example, for a list of integers, this return * list[int], while getType returns list. Both methods are needed so type([1,2,3]) is type(['a', 'b', 'c']) * return True. * * @return the generic version of this object's type. Must not be used in identity checks. */ default PythonLikeType $getGenericType() { return $getType(); } default PythonLikeObject $method$__getattribute__(PythonString pythonName) { String name = pythonName.value; PythonLikeObject objectResult = $getAttributeOrNull(name); if (objectResult != null) { return objectResult; } PythonLikeType type = $getType(); PythonLikeObject typeResult = type.$getAttributeOrNull(name); if (typeResult != null) { PythonLikeObject maybeDescriptor = typeResult.$getAttributeOrNull(PythonTernaryOperator.GET.dunderMethod); if (maybeDescriptor == null) { maybeDescriptor = typeResult.$getType().$getAttributeOrNull(PythonTernaryOperator.GET.dunderMethod); } if (maybeDescriptor != null) { if (!(maybeDescriptor instanceof PythonLikeFunction)) { throw new UnsupportedOperationException("'" + maybeDescriptor.$getType() + "' is not callable"); } return TernaryDunderBuiltin.GET_DESCRIPTOR.invoke(typeResult, this, type); } return typeResult; } throw new AttributeError("object '" + this + "' does not have attribute '" + name + "'"); } default PythonLikeObject $method$__setattr__(PythonString pythonName, PythonLikeObject value) { String name = pythonName.value; $setAttribute(name, value); return PythonNone.INSTANCE; } default PythonLikeObject $method$__delattr__(PythonString pythonName) { String name = pythonName.value; $deleteAttribute(name); return PythonNone.INSTANCE; } default PythonLikeObject $method$__eq__(PythonLikeObject other) { return PythonBoolean.valueOf(Objects.equals(this, other)); } default PythonLikeObject $method$__ne__(PythonLikeObject other) { return PythonBoolean.valueOf(!Objects.equals(this, other)); } default PythonString $method$__str__() { return PythonString.valueOf(this.getClass().getSimpleName() + "@" + System.identityHashCode(this)); } default PythonLikeObject $method$__repr__() { String position; if (this instanceof CPythonBackedPythonLikeObject) { PythonInteger id = ((CPythonBackedPythonLikeObject) this).$cpythonId; if (id != null) { position = id.toString(); } else { position = String.valueOf(System.identityHashCode(this)); } } else { position = String.valueOf(System.identityHashCode(this)); } return PythonString.valueOf("<" + $getType().getTypeName() + " object at " + position + ">"); } default PythonLikeObject $method$__format__() { return $method$__format__(PythonNone.INSTANCE); } default PythonLikeObject $method$__format__(PythonLikeObject formatString) { return $method$__str__().$method$__format__(formatString); } default PythonLikeObject $method$__hash__() { throw new TypeError("unhashable type: '" + $getType().getTypeName() + "'"); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonOverloadImplementor.java
package ai.timefold.jpyinterpreter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.SortedMap; import java.util.TreeMap; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.implementors.KnownCallImplementor; import ai.timefold.jpyinterpreter.types.BoundPythonLikeFunction; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonKnownFunctionType; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.util.MethodVisitorAdapters; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class PythonOverloadImplementor { public static Comparator<PythonLikeType> TYPE_DEPTH_COMPARATOR = Comparator.comparingInt(PythonLikeType::getDepth) .thenComparing(PythonLikeType::getTypeName) .thenComparing(PythonLikeType::getJavaTypeInternalName) .reversed(); private final static List<DeferredRunner> deferredRunnerList = new ArrayList<>(); public interface DeferredRunner { PythonLikeType run() throws NoSuchMethodException; } public static void deferDispatchesFor(DeferredRunner runner) { try { createDispatchesFor(runner.run()); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } // deferredRunnerList.add(runner); } public static void createDeferredDispatches() { while (!deferredRunnerList.isEmpty()) { List<DeferredRunner> deferredRunnables = new ArrayList<>(deferredRunnerList); List<PythonLikeType> deferredTypes = new ArrayList<>(deferredRunnables.size()); deferredRunnables.forEach(runner -> { try { deferredTypes.add(runner.run()); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } }); deferredTypes.forEach(PythonOverloadImplementor::createDispatchesFor); deferredRunnerList.subList(0, deferredRunnables.size()).clear(); } } public static void createDispatchesFor(PythonLikeType pythonLikeType) { for (String methodName : pythonLikeType.getKnownMethodsDefinedByClass()) { PythonLikeFunction overloadDispatch = createDispatchForMethod(pythonLikeType, methodName, pythonLikeType.getMethodType(methodName).orElseThrow(), pythonLikeType.getMethodKind(methodName) .orElse(PythonClassTranslator.PythonMethodKind.VIRTUAL_METHOD)); pythonLikeType.$setAttribute(methodName, overloadDispatch); } if (pythonLikeType.getConstructorType().isPresent()) { PythonLikeFunction overloadDispatch = createDispatchForMethod(pythonLikeType, "__init__", pythonLikeType.getConstructorType().orElseThrow(), PythonClassTranslator.PythonMethodKind.VIRTUAL_METHOD); pythonLikeType.setConstructor(overloadDispatch); pythonLikeType.$setAttribute("__init__", overloadDispatch); } } private static PythonLikeFunction createDispatchForMethod(PythonLikeType pythonLikeType, String methodName, PythonKnownFunctionType knownFunctionType, PythonClassTranslator.PythonMethodKind methodKind) { String maybeClassName = PythonBytecodeToJavaBytecodeTranslator.GENERATED_PACKAGE_BASE + pythonLikeType.getJavaTypeInternalName().replace('/', '.') + "." + methodName + "$$Dispatcher"; int numberOfInstances = PythonBytecodeToJavaBytecodeTranslator.classNameToSharedInstanceCount.merge(maybeClassName, 1, Integer::sum); if (numberOfInstances > 1) { maybeClassName = maybeClassName + "$$" + numberOfInstances; } String className = maybeClassName; String internalClassName = className.replace('.', '/'); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V11, Modifier.PUBLIC, internalClassName, null, Type.getInternalName(Object.class), new String[] { Type.getInternalName(PythonLikeFunction.class) }); // No args constructor for creating instance of this class MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), null, null); methodVisitor.visitCode(); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitInsn(Opcodes.RETURN); methodVisitor.visitMaxs(-1, -1); methodVisitor.visitEnd(); createDispatchFunction(pythonLikeType, knownFunctionType, classWriter); createGetTypeFunction(methodKind, classWriter); classWriter.visitEnd(); PythonBytecodeToJavaBytecodeTranslator.writeClassOutput(BuiltinTypes.classNameToBytecode, className, classWriter.toByteArray()); try { Class<? extends PythonLikeFunction> generatedClass = (Class<? extends PythonLikeFunction>) BuiltinTypes.asmClassLoader.loadClass(className); return generatedClass.getConstructor().newInstance(); } catch (ClassNotFoundException e) { throw new IllegalStateException("Impossible State: Unable to load generated class (" + className + ") despite it being just generated.", e); } catch (InvocationTargetException | InstantiationException | NoSuchMethodException | IllegalAccessException e) { throw new IllegalStateException("Impossible State: Unable to invoke constructor for generated class (" + className + ").", e); } } private static void createGetTypeFunction(PythonClassTranslator.PythonMethodKind kind, ClassWriter classWriter) { MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), null, null); methodVisitor.visitCode(); switch (kind) { case VIRTUAL_METHOD: methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(BuiltinTypes.class), "FUNCTION_TYPE", Type.getDescriptor(PythonLikeType.class)); break; case STATIC_METHOD: methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(BuiltinTypes.class), "STATIC_FUNCTION_TYPE", Type.getDescriptor(PythonLikeType.class)); break; case CLASS_METHOD: methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(BuiltinTypes.class), "CLASS_FUNCTION_TYPE", Type.getDescriptor(PythonLikeType.class)); break; default: throw new IllegalStateException("Unhandled case: " + kind); } methodVisitor.visitInsn(Opcodes.ARETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } private static void createDispatchFunction(PythonLikeType type, PythonKnownFunctionType knownFunctionType, ClassWriter classWriter) { MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), null, null); methodVisitor = MethodVisitorAdapters.adapt(methodVisitor, "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class))); methodVisitor.visitParameter("positionalArguments", 0); methodVisitor.visitParameter("namedArguments", 0); methodVisitor.visitParameter("callerInstance", 0); methodVisitor.visitCode(); List<PythonFunctionSignature> overloadList = knownFunctionType.getOverloadFunctionSignatureList(); Map<Integer, List<PythonFunctionSignature>> pythonFunctionSignatureByArgumentLength = overloadList.stream() .filter(sig -> sig.getExtraPositionalArgumentsVariableIndex().isEmpty() && sig.getExtraKeywordArgumentsVariableIndex().isEmpty()) .collect(Collectors.groupingBy(sig -> sig.getParameterTypes().length)); Optional<PythonFunctionSignature> maybeGenericFunctionSignature = overloadList.stream() .findAny(); if (overloadList.get(0).isFromArgumentSpec() || pythonFunctionSignatureByArgumentLength.isEmpty()) { // only generic overload // No error message since we MUST have a generic overload createGenericDispatch(methodVisitor, type, maybeGenericFunctionSignature, ""); } else { int[] argCounts = pythonFunctionSignatureByArgumentLength.keySet().stream().sorted().mapToInt(i -> i).toArray(); Label[] argCountLabel = new Label[argCounts.length]; Label defaultCase = new Label(); for (int i = 0; i < argCountLabel.length; i++) { argCountLabel[i] = new Label(); } methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "size", Type.getMethodDescriptor(Type.INT_TYPE), true); if (!overloadList.get(0).getMethodDescriptor().getMethodType().isStatic()) { methodVisitor.visitInsn(Opcodes.ICONST_M1); methodVisitor.visitInsn(Opcodes.IADD); } methodVisitor.visitLookupSwitchInsn(defaultCase, argCounts, argCountLabel); for (int i = 0; i < argCounts.length; i++) { methodVisitor.visitLabel(argCountLabel[i]); createDispatchForArgCount(methodVisitor, argCounts[i], type, pythonFunctionSignatureByArgumentLength.get(argCounts[i]), maybeGenericFunctionSignature); } methodVisitor.visitLabel(defaultCase); createGenericDispatch(methodVisitor, type, maybeGenericFunctionSignature, "No overload has the given argcount. Possible overload(s) are: " + knownFunctionType.getOverloadFunctionSignatureList().stream().map(PythonFunctionSignature::toString) .collect(Collectors.joining(",\n"))); } methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } private static void createDispatchForArgCount(MethodVisitor methodVisitor, int argCount, PythonLikeType type, List<PythonFunctionSignature> functionSignatureList, Optional<PythonFunctionSignature> maybeGenericDispatch) { final int MATCHING_OVERLOAD_SET_VARIABLE_INDEX = 3; // 0 = this; 1 = posArguments; 2 = namedArguments methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(HashSet.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(functionSignatureList.size()); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(HashSet.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE), false); for (int i = 0; i < functionSignatureList.size(); i++) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(i); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Integer.class), "valueOf", Type.getMethodDescriptor(Type.getType(Integer.class), Type.INT_TYPE), false); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "add", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), true); methodVisitor.visitInsn(Opcodes.POP); } methodVisitor.visitVarInsn(Opcodes.ASTORE, MATCHING_OVERLOAD_SET_VARIABLE_INDEX); int startIndex = 0; if (!functionSignatureList.get(0).getMethodDescriptor().getMethodType().isStatic()) { startIndex = 1; } methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); // At the start of each iteration, stack = arg_1, arg_2, ..., arg_(i-1), pos_args_list for (int i = 0; i < argCount; i++) { methodVisitor.visitInsn(Opcodes.DUP); // Get the ith positional argument methodVisitor.visitLdcInsn(i + startIndex); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); SortedMap<PythonLikeType, List<PythonFunctionSignature>> typeToPossibleSignatures = getTypeForParameter(functionSignatureList, i); Label endOfInstanceOfIfs = new Label(); for (PythonLikeType pythonLikeType : typeToPossibleSignatures.keySet()) { Label nextIf = new Label(); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, pythonLikeType.getJavaTypeInternalName()); methodVisitor.visitJumpInsn(Opcodes.IFEQ, nextIf); // pythonLikeType matches argument type List<PythonFunctionSignature> matchingOverloadList = typeToPossibleSignatures.get(pythonLikeType); if (matchingOverloadList.size() != functionSignatureList.size()) { // Remove overloads that do not match from the matching overload set methodVisitor.visitVarInsn(Opcodes.ALOAD, MATCHING_OVERLOAD_SET_VARIABLE_INDEX); for (int sigIndex = 0; sigIndex < functionSignatureList.size(); sigIndex++) { if (!matchingOverloadList.contains(functionSignatureList.get(sigIndex))) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(sigIndex); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Integer.class), "valueOf", Type.getMethodDescriptor(Type.getType(Integer.class), Type.INT_TYPE), false); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "remove", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), true); methodVisitor.visitInsn(Opcodes.POP); } } methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfInstanceOfIfs); } else { methodVisitor.visitJumpInsn(Opcodes.GOTO, endOfInstanceOfIfs); } methodVisitor.visitLabel(nextIf); } // This is an else at the end of the instanceof if's, which clear the set as no overloads match methodVisitor.visitVarInsn(Opcodes.ALOAD, MATCHING_OVERLOAD_SET_VARIABLE_INDEX); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "clear", Type.getMethodDescriptor(Type.VOID_TYPE), true); // end of instance of ifs methodVisitor.visitLabel(endOfInstanceOfIfs); methodVisitor.visitInsn(Opcodes.POP); // remove argument (need to typecast it later) } methodVisitor.visitInsn(Opcodes.POP); // Remove list // Stack is arg_1, arg_2, ..., arg_(argCount) methodVisitor.visitVarInsn(Opcodes.ALOAD, MATCHING_OVERLOAD_SET_VARIABLE_INDEX); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "size", Type.getMethodDescriptor(Type.INT_TYPE), true); Label setIsNotEmpty = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFNE, setIsNotEmpty); createGenericDispatch(methodVisitor, type, maybeGenericDispatch, "No overload match the given arguments. Possible overload(s) for " + argCount + " arguments are: " + functionSignatureList.stream().map(PythonFunctionSignature::toString) .collect(Collectors.joining(",\n"))); methodVisitor.visitLabel(setIsNotEmpty); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Iterable.class), "iterator", Type.getMethodDescriptor(Type.getType(Iterator.class)), true); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Iterator.class), "next", Type.getMethodDescriptor(Type.getType(Object.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Integer.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Integer.class), "intValue", Type.getMethodDescriptor(Type.INT_TYPE), false); Label defaultHandler = new Label(); Label[] signatureIndexToDispatch = new Label[functionSignatureList.size()]; for (int i = 0; i < functionSignatureList.size(); i++) { signatureIndexToDispatch[i] = new Label(); } methodVisitor.visitTableSwitchInsn(0, functionSignatureList.size() - 1, defaultHandler, signatureIndexToDispatch); for (int i = 0; i < functionSignatureList.size(); i++) { methodVisitor.visitLabel(signatureIndexToDispatch[i]); PythonFunctionSignature matchingSignature = functionSignatureList.get(i); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); if (startIndex != 0) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(0); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, matchingSignature.getMethodDescriptor().getDeclaringClassInternalName()); methodVisitor.visitInsn(Opcodes.SWAP); } for (int argIndex = 0; argIndex < argCount; argIndex++) { PythonLikeType parameterType = matchingSignature.getParameterTypes()[argIndex]; methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(argIndex + startIndex); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, parameterType.getJavaTypeInternalName()); methodVisitor.visitInsn(Opcodes.SWAP); } methodVisitor.visitInsn(Opcodes.POP); matchingSignature.getMethodDescriptor().callMethod(methodVisitor); methodVisitor.visitInsn(Opcodes.ARETURN); } methodVisitor.visitLabel(defaultHandler); methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalStateException.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn("Return signature index is out of bounds"); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalStateException.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.ATHROW); } private static void createGenericDispatch(MethodVisitor methodVisitor, PythonLikeType type, Optional<PythonFunctionSignature> maybeGenericDispatch, String errorMessage) { if (maybeGenericDispatch.isEmpty()) { methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(TypeError.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(StringBuilder.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(StringBuilder.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonOverloadImplementor.class), "getCallErrorInfo", Type.getMethodDescriptor(Type.getType(String.class), Type.getType(List.class), Type.getType(Map.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.getType(String.class)), false); methodVisitor.visitLdcInsn(errorMessage); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.getType(String.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "toString", Type.getMethodDescriptor(Type.getType(String.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(TypeError.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.ATHROW); } else { PythonFunctionSignature functionSignature = maybeGenericDispatch.get(); if (functionSignature.getMethodDescriptor().getMethodType() != MethodDescriptor.MethodType.STATIC) { // It a class/virtual method, so need to load instance/type from argument list methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitLdcInsn(0); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeObject.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); if (functionSignature.getMethodDescriptor().getMethodType() == MethodDescriptor.MethodType.CLASS) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(BoundPythonLikeFunction.class), "boundToTypeOfObject", Type.getMethodDescriptor(Type.getType(BoundPythonLikeFunction.class), Type.getType(PythonLikeObject.class), Type.getType(PythonLikeFunction.class)), false); } else { methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(BoundPythonLikeFunction.class)); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(BoundPythonLikeFunction.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeObject.class), Type.getType(PythonLikeFunction.class)), false); } // Load the sublist without the self/type argument methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "size", Type.getMethodDescriptor(Type.INT_TYPE), true); methodVisitor.visitLdcInsn(1); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "subList", Type.getMethodDescriptor(Type.getType(List.class), Type.INT_TYPE, Type.INT_TYPE), true); } else { methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); } methodVisitor.visitVarInsn(Opcodes.ALOAD, 2); KnownCallImplementor.callUnpackListAndMap(functionSignature.getDefaultArgumentHolderClassInternalName(), functionSignature.getMethodDescriptor(), methodVisitor); methodVisitor.visitInsn(Opcodes.ARETURN); } } public static String getCallErrorInfo(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> namedArgs) { return "Could not find an overload that accept " + positionalArgs.stream() .map(arg -> arg.$getType().getTypeName()).collect(Collectors.joining(", ", "(", ") argument types. ")); } private static SortedMap<PythonLikeType, List<PythonFunctionSignature>> getTypeForParameter(List<PythonFunctionSignature> functionSignatureList, int parameter) { SortedMap<PythonLikeType, List<PythonFunctionSignature>> out = new TreeMap<>(TYPE_DEPTH_COMPARATOR); for (PythonFunctionSignature functionSignature : functionSignatureList) { out.computeIfAbsent(functionSignature.getParameterTypes()[parameter], type -> new ArrayList<>()) .add(functionSignature); } return out; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonTernaryOperator.java
package ai.timefold.jpyinterpreter; /** * The list of all Python Ternary Operators, which take * self and two other arguments. * * ex: a.__setitem__(key, value) */ public enum PythonTernaryOperator { // Descriptor operations // https://docs.python.org/3/howto/descriptor.html GET("__get__"), SET("__set__"), // Attribute access SET_ATTRIBUTE("__setattr__"), // List operations // https://docs.python.org/3/reference/datamodel.html#object.__setitem__ SET_ITEM("__setitem__"); public final String dunderMethod; PythonTernaryOperator(String dunderMethod) { this.dunderMethod = dunderMethod; } public String getDunderMethod() { return dunderMethod; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonUnaryOperator.java
package ai.timefold.jpyinterpreter; /** * The list of all Python Unary Operators, which take * self as the only argument. * * ex: a.__neg__() */ public enum PythonUnaryOperator { NEGATIVE("__neg__"), POSITIVE("__pos__"), ABS("__abs__"), INVERT("__invert__"), ITERATOR("__iter__"), AS_BOOLEAN("__bool__"), AS_FLOAT("__float__"), AS_INT("__int__"), AS_INDEX("__index__"), AS_STRING("__str__"), REPRESENTATION("__repr__"), ENTER("__enter__"), LENGTH("__len__"), NEXT("__next__"), REVERSED("__reversed__"), HASH("__hash__"); final String dunderMethod; PythonUnaryOperator(String dunderMethod) { this.dunderMethod = dunderMethod; } public String getDunderMethod() { return dunderMethod; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/PythonVersion.java
package ai.timefold.jpyinterpreter; import java.util.Objects; public final class PythonVersion implements Comparable<PythonVersion> { private final int hexversion; public static final PythonVersion PYTHON_3_10 = new PythonVersion(3, 10); public static final PythonVersion PYTHON_3_11 = new PythonVersion(3, 11); public static final PythonVersion PYTHON_3_12 = new PythonVersion(3, 12); public static final PythonVersion MINIMUM_PYTHON_VERSION = PYTHON_3_10; public PythonVersion(int hexversion) { this.hexversion = hexversion; } public PythonVersion(int major, int minor) { // Select the final version for the first Python release with the given major and minor this(major, minor, 0); } public PythonVersion(int major, int minor, int micro) { // Select the final version for the first Python release with the given major, minor and micro this((major << (8 * 3)) + (minor << (8 * 2)) + (micro << 8) + 0xF0); } public int getMajorVersion() { return (hexversion & 0xFF000000) >> (8 * 3); } public int getMinorVersion() { return (hexversion & 0x00FF0000) >> (8 * 2); } public int getMicroVersion() { return (hexversion & 0x0000FF00) >> 8; } public int getReleaseLevel() { return (hexversion & 0x000000F0) >> 4; } public int getReleaseSerial() { return (hexversion & 0x0000000F); } @Override public int compareTo(PythonVersion pythonVersion) { return hexversion - pythonVersion.hexversion; } public boolean isBefore(PythonVersion release) { return compareTo(release) < 0; } public boolean isAfter(PythonVersion release) { return compareTo(release) > 0; } public boolean isAtLeast(PythonVersion release) { return compareTo(release) >= 0; } public boolean isBetween(PythonVersion afterInclusive, PythonVersion beforeInclusive) { return compareTo(afterInclusive) >= 0 && compareTo(beforeInclusive) <= 0; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PythonVersion that = (PythonVersion) o; return hexversion == that.hexversion; } @Override public int hashCode() { return Objects.hash(hexversion); } public String toString() { return getMajorVersion() + "." + getMinorVersion() + "." + getMinorVersion() + getReleaseLevelString() + getReleaseSerial(); } private String getReleaseLevelString() { switch (getReleaseLevel()) { case 0xA: return "a"; // Alpha release case 0xB: return "b"; // Beta release case 0xC: return "rc"; // Release Candidate case 0xF: return ""; // Final default: // https://docs.python.org/3/c-api/apiabiversion.html#apiabiversion // only use 4 states out of the possible 16. return ("<" + getReleaseLevel() + ">"); } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/StackMetadata.java
package ai.timefold.jpyinterpreter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.opcodes.OpcodeWithoutSource; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class StackMetadata { public static final StackMetadata DEAD_CODE = new StackMetadata(); public final LocalVariableHelper localVariableHelper; private final List<ValueSourceInfo> stackValueSources; private final List<ValueSourceInfo> localVariableValueSources; private final List<ValueSourceInfo> cellVariableValueSources; private List<String> callKeywordNameList; private StackMetadata() { this.localVariableHelper = null; this.stackValueSources = null; this.localVariableValueSources = null; this.cellVariableValueSources = null; this.callKeywordNameList = null; } public StackMetadata(LocalVariableHelper localVariableHelper) { this.localVariableHelper = localVariableHelper; this.stackValueSources = new ArrayList<>(); this.localVariableValueSources = new ArrayList<>(localVariableHelper.getNumberOfLocalVariables()); this.cellVariableValueSources = new ArrayList<>(localVariableHelper.getNumberOfCells()); for (int i = 0; i < localVariableHelper.getNumberOfLocalVariables(); i++) { localVariableValueSources.add(null); } for (int i = 0; i < localVariableHelper.getNumberOfCells(); i++) { cellVariableValueSources.add(ValueSourceInfo.of(new OpcodeWithoutSource(), BuiltinTypes.BASE_TYPE)); } this.callKeywordNameList = Collections.emptyList(); } private StackMetadata(LocalVariableHelper localVariableHelper, List<ValueSourceInfo> stackValueSources, List<ValueSourceInfo> localVariableValueSources, List<ValueSourceInfo> cellVariableValueSources, List<String> callKeywordNameList) { this.localVariableHelper = localVariableHelper; this.stackValueSources = stackValueSources; this.localVariableValueSources = localVariableValueSources; this.cellVariableValueSources = cellVariableValueSources; this.callKeywordNameList = callKeywordNameList; } public boolean isDeadCode() { return this == DEAD_CODE; } public int getStackSize() { return stackValueSources.size(); } /** * Returns the list index for the given stack index (stack index is how many * elements below TOS (i.e. 0 is TOS, 1 is TOS1)). * * @param stackIndex The stack index (how many elements below TOS) * @return The corresponding list index corresponding to the element at the given distance from TOS * (i.e. STACK_SIZE - distance - 1) */ private int getListIndexForStackIndex(int stackIndex) { return stackValueSources.size() - stackIndex - 1; } /** * Returns the value source for the given stack index (stack index is how many * elements below TOS (i.e. 0 is TOS, 1 is TOS1)). * * @param index The stack index (how many elements below TOS) * @return The type at the given stack index */ public ValueSourceInfo getValueSourceForStackIndex(int index) { return stackValueSources.get(getListIndexForStackIndex(index)); } /** * Returns the value sources up to (and not including) the given stack index (stack index is how many * elements below TOS (i.e. 0 is TOS, 1 is TOS1)). * * @param index The stack index (how many elements below TOS) * @return The value sources up to (and not including) the given stack index */ public List<ValueSourceInfo> getValueSourcesUpToStackIndex(int index) { return stackValueSources.subList(stackValueSources.size() - index, stackValueSources.size()); } /** * Returns the type at the given stack index (stack index is how many * elements below TOS (i.e. 0 is TOS, 1 is TOS1)). * * @param index The stack index (how many elements below TOS) * @return The type at the given stack index */ public PythonLikeType getTypeAtStackIndex(int index) { ValueSourceInfo valueSourceInfo = stackValueSources.get(getListIndexForStackIndex(index)); if (valueSourceInfo != null) { return valueSourceInfo.valueType; } // Unknown type return BuiltinTypes.BASE_TYPE; } /** * Returns the value source for the local variable in slot {@code index} * * @param index The slot * @return The type for the local variable in the given slot */ public ValueSourceInfo getLocalVariableValueSource(int index) { return localVariableValueSources.get(index); } /** * Returns the value source for the cell variable in slot {@code index} * * @param index The slot * @return The type for the cell variable in the given slot */ public ValueSourceInfo getCellVariableValueSource(int index) { return cellVariableValueSources.get(index); } public PythonLikeType getTOSType() { return getTypeAtStackIndex(0); } public ValueSourceInfo getTOSValueSource() { return getValueSourceForStackIndex(0); } public StackMetadata copy() { StackMetadata out = new StackMetadata(localVariableHelper, new ArrayList<>(stackValueSources), new ArrayList<>(localVariableValueSources), new ArrayList<>(cellVariableValueSources), callKeywordNameList); return out; } public StackMetadata unifyWith(StackMetadata other) { if (this == DEAD_CODE) { return other; } if (other == DEAD_CODE) { return this; } StackMetadata out = copy(); if (out.stackValueSources.size() != other.stackValueSources.size() || out.localVariableValueSources.size() != other.localVariableValueSources.size() || out.cellVariableValueSources.size() != other.cellVariableValueSources.size()) { throw new IllegalArgumentException("Impossible State: Bytecode stack metadata size does not match when " + "unifying (" + out.stackValueSources.stream() .map(valueSource -> valueSource.valueType.toString()).collect(Collectors.joining(", ", "[", "]")) + ") with (" + other.stackValueSources.stream() .map(valueSource -> valueSource.valueType.toString()).collect(Collectors.joining(", ", "[", "]")) + ")"); } for (int i = 0; i < out.stackValueSources.size(); i++) { out.stackValueSources.set(i, unifyTypes(stackValueSources.get(i), other.stackValueSources.get(i))); } for (int i = 0; i < out.localVariableValueSources.size(); i++) { out.localVariableValueSources.set(i, unifyTypes(localVariableValueSources.get(i), other.localVariableValueSources.get(i))); } for (int i = 0; i < out.cellVariableValueSources.size(); i++) { out.cellVariableValueSources.set(i, unifyTypes(cellVariableValueSources.get(i), other.cellVariableValueSources.get(i))); } return out; } private static ValueSourceInfo unifyTypes(ValueSourceInfo a, ValueSourceInfo b) { if (Objects.equals(a, b)) { return a; } if (a == null) { // a or b are null when they are deleted/are not set yet return b; // TODO: Optional type? } if (b == null) { return a; } return a.unifyWith(b); } /** * Return a new StackMetadata with {@code type} added as the new * TOS element. * * @param type The type to push to TOS */ public StackMetadata push(ValueSourceInfo type) { StackMetadata out = copy(); out.stackValueSources.add(type); return out; } public StackMetadata set(int index, ValueSourceInfo type) { StackMetadata out = copy(); out.stackValueSources.set(getListIndexForStackIndex(index), type); return out; } public StackMetadata pushTemp(PythonLikeType type) { return push(ValueSourceInfo.of(new OpcodeWithoutSource(), type)); } /** * Return a new StackMetadata with {@code types} added as the new * elements. The last element of {@code types} is TOS. * * @param types The types to push to TOS */ public StackMetadata push(ValueSourceInfo... types) { StackMetadata out = copy(); out.stackValueSources.addAll(Arrays.asList(types)); return out; } public StackMetadata pushTemps(PythonLikeType... types) { StackMetadata out = copy(); for (PythonLikeType type : types) { out.stackValueSources.add(ValueSourceInfo.of(new OpcodeWithoutSource(), type)); } return out; } /** * Return a new StackMetadata with {@code types} as the stack; * The original stack is cleared. * * @param types The stack types. */ public StackMetadata stack(ValueSourceInfo... types) { StackMetadata out = copy(); out.stackValueSources.clear(); out.stackValueSources.addAll(Arrays.asList(types)); return out; } /** * Return a new StackMetadata with TOS popped */ public StackMetadata pop() { StackMetadata out = copy(); out.stackValueSources.remove(stackValueSources.size() - 1); return out; } /** * Return a new StackMetadata with the top {@code count} items popped. */ public StackMetadata pop(int count) { StackMetadata out = copy(); out.stackValueSources.subList(stackValueSources.size() - count, stackValueSources.size()).clear(); return out; } /** * Return a new StackMetadata with the local variable in slot {@code index} type set to * {@code type}. */ public StackMetadata setLocalVariableValueSource(int index, ValueSourceInfo type) { StackMetadata out = copy(); out.localVariableValueSources.set(index, type); return out; } /** * Return a new StackMetadata with the given local types. Throws {@link IllegalArgumentException} if * types.length != localVariableTypes.size(). */ public StackMetadata locals(ValueSourceInfo... types) { if (types.length != localVariableValueSources.size()) { throw new IllegalArgumentException( "Length mismatch: expected an array with {" + localVariableValueSources.size() + "} elements but got " + "{" + Arrays.toString(types) + "}"); } StackMetadata out = copy(); for (int i = 0; i < types.length; i++) { out.localVariableValueSources.set(i, types[i]); } return out; } /** * Return a new StackMetadata with the cell variable in slot {@code index} type set to * {@code type}. */ public StackMetadata setCellVariableValueSource(int index, ValueSourceInfo type) { StackMetadata out = copy(); out.cellVariableValueSources.set(index, type); return out; } public List<String> getCallKeywordNameList() { return callKeywordNameList; } public StackMetadata setCallKeywordNameList(List<String> callKeywordNameList) { StackMetadata out = copy(); out.callKeywordNameList = callKeywordNameList; return out; } public String toString() { return "StackMetadata { stack: " + stackValueSources.toString() + "; locals: " + localVariableValueSources.toString() + "; cells: " + cellVariableValueSources.toString() + "; }"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (this == DEAD_CODE || o == DEAD_CODE) { return false; // this != o and one is DEAD_CODE } StackMetadata that = (StackMetadata) o; return stackValueSources.equals(that.stackValueSources) && localVariableValueSources.equals(that.localVariableValueSources) && cellVariableValueSources.equals(that.cellVariableValueSources); } @Override public int hashCode() { return Objects.hash(stackValueSources, localVariableValueSources, cellVariableValueSources); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/TypeHint.java
package ai.timefold.jpyinterpreter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import ai.timefold.jpyinterpreter.types.PythonLikeType; import org.jspecify.annotations.Nullable; import org.objectweb.asm.Type; public record TypeHint(PythonLikeType type, List<AnnotationMetadata> annotationList, TypeHint[] genericArgs, PythonLikeType javaGetterType) { public TypeHint { annotationList = Collections.unmodifiableList(annotationList); } public TypeHint(PythonLikeType type, List<AnnotationMetadata> annotationList) { this(type, annotationList, null, type); } public TypeHint(PythonLikeType type, List<AnnotationMetadata> annotationList, PythonLikeType javaGetterType) { this(type, annotationList, null, javaGetterType); } @Nullable public String getOverrideTypeDescriptor() { Class<?> override = null; for (var annotation : annotationList) { var newOverride = annotation.fieldTypeOverride(); if (override != null && !override.equals(newOverride)) { throw new IllegalArgumentException( "Multiple override specified that do not match in annotations (" + annotationList + ")."); } override = newOverride; } return (override != null) ? Type.getDescriptor(override) : null; } public TypeHint addAnnotations(List<AnnotationMetadata> addedAnnotations) { List<AnnotationMetadata> combinedAnnotations = new ArrayList<>(annotationList.size() + addedAnnotations.size()); combinedAnnotations.addAll(annotationList); combinedAnnotations.addAll(addedAnnotations); return new TypeHint(type, combinedAnnotations, genericArgs, javaGetterType); } public static TypeHint withoutAnnotations(PythonLikeType type) { return new TypeHint(type, Collections.emptyList()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TypeHint typeHint)) { return false; } return Objects.equals(type, typeHint.type) && Objects.deepEquals(genericArgs, typeHint.genericArgs) && Objects.equals(javaGetterType, typeHint.javaGetterType) && Objects.equals(annotationList, typeHint.annotationList); } @Override public int hashCode() { return Objects.hash(type, annotationList, Arrays.hashCode(genericArgs), javaGetterType); } @Override public String toString() { return "TypeHint{" + "type=" + type + ", annotationList=" + annotationList + ", genericArgs=" + Arrays.toString(genericArgs) + ", javaGetterType=" + javaGetterType + '}'; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/ValueSourceInfo.java
package ai.timefold.jpyinterpreter; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class ValueSourceInfo { final PythonLikeType valueType; final Set<Opcode> possibleSourceOpcodeSet; final Set<ValueSourceInfo> valueDependencySet; private ValueSourceInfo(PythonLikeType valueType, Set<Opcode> possibleSourceOpcodeSet, Set<ValueSourceInfo> valueDependencySet) { this.valueType = valueType; this.possibleSourceOpcodeSet = possibleSourceOpcodeSet; this.valueDependencySet = valueDependencySet; } public PythonLikeType getValueType() { return valueType; } public Set<Opcode> getPossibleSourceOpcodeSet() { return possibleSourceOpcodeSet; } public Set<ValueSourceInfo> getValueDependencySet() { return valueDependencySet; } public ValueSourceInfo unifyWith(ValueSourceInfo other) { PythonLikeType newValueType = valueType.unifyWith(other.valueType); Set<Opcode> newPossibleSourceOpcodeSet = new HashSet<>(possibleSourceOpcodeSet.size() + other.possibleSourceOpcodeSet.size()); newPossibleSourceOpcodeSet.addAll(possibleSourceOpcodeSet); newPossibleSourceOpcodeSet.addAll(other.possibleSourceOpcodeSet); Set<ValueSourceInfo> newValueDependencySet = new HashSet<>(valueDependencySet.size() + other.valueDependencySet.size()); newValueDependencySet.addAll(valueDependencySet); for (ValueSourceInfo dependency : other.valueDependencySet) { Optional<ValueSourceInfo> maybeCommonDependency = valueDependencySet.stream() .filter(otherValueSource -> otherValueSource.possibleSourceOpcodeSet .equals(dependency.getPossibleSourceOpcodeSet())) .findAny(); // If it is not empty, it was added in the previous loop if (maybeCommonDependency.isEmpty()) { newValueDependencySet.add(dependency); } } return new ValueSourceInfo(newValueType, newPossibleSourceOpcodeSet, newValueDependencySet); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ValueSourceInfo that = (ValueSourceInfo) o; return valueType.equals(that.valueType) && possibleSourceOpcodeSet.equals(that.possibleSourceOpcodeSet) && valueDependencySet.equals(that.valueDependencySet); } @Override public int hashCode() { return Objects.hash(valueType, possibleSourceOpcodeSet, valueDependencySet); } @Override public String toString() { return "ValueSourceInfo{" + "valueType=" + valueType + ", possibleSourceOpcodeList=" + possibleSourceOpcodeSet + ", valueDependencyList=" + valueDependencySet + '}'; } public static ValueSourceInfo of(Opcode sourceOpcode, PythonLikeType valueType, ValueSourceInfo... dependencies) { return new ValueSourceInfo(valueType, Set.of(sourceOpcode), Set.of(dependencies)); } public static ValueSourceInfo of(Opcode sourceOpcode, PythonLikeType valueType, List<ValueSourceInfo> dependencyList) { return new ValueSourceInfo(valueType, Set.of(sourceOpcode), new HashSet<>(dependencyList)); } }