index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/TaskRunEnv.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema;
import ai.databand.schema.jackson.ZonedDateTimeDeserializer;
import ai.databand.schema.jackson.ZonedDateTimeSerializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.time.ZonedDateTime;
public class TaskRunEnv {
private String userData;
private String uid;
private String user;
private String userCodeVersion;
private String machine;
private String cmdLine;
@JsonSerialize(using = ZonedDateTimeSerializer.class)
@JsonDeserialize(using = ZonedDateTimeDeserializer.class)
private ZonedDateTime heartbeat;
private String databand_version;
private String projectRoot;
private boolean userCodeCommitted;
public TaskRunEnv(String userData, String uid, String user, String userCodeVersion, String machine, String cmdLine, ZonedDateTime heartbeat, String databand_version, String projectRoot, boolean userCodeCommitted) {
this.userData = userData;
this.uid = uid;
this.user = user;
this.userCodeVersion = userCodeVersion;
this.machine = machine;
this.cmdLine = cmdLine;
this.heartbeat = heartbeat;
this.databand_version = databand_version;
this.projectRoot = projectRoot;
this.userCodeCommitted = userCodeCommitted;
}
public String getUserData() {
return userData;
}
public String getUid() {
return uid;
}
public String getUser() {
return user;
}
public String getUserCodeVersion() {
return userCodeVersion;
}
public String getMachine() {
return machine;
}
public String getCmdLine() {
return cmdLine;
}
public ZonedDateTime getHeartbeat() {
return heartbeat;
}
public String getDataband_version() {
return databand_version;
}
public String getProjectRoot() {
return projectRoot;
}
public boolean isUserCodeCommitted() {
return userCodeCommitted;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/TaskRunParam.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public class TaskRunParam {
private String name;
private String value;
private String valueOrigin;
private String parameterName;
private List<String> targetsUids;
public TaskRunParam() {
}
public TaskRunParam(String value, String valueOrigin, String parameterName) {
this.value = value;
this.valueOrigin = valueOrigin;
this.parameterName = parameterName;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getValueOrigin() {
return valueOrigin;
}
public void setValueOrigin(String valueOrigin) {
this.valueOrigin = valueOrigin;
}
public String getParameterName() {
return parameterName;
}
public void setParameterName(String parameterName) {
this.parameterName = parameterName;
}
public List<String> getTargetsUids() {
return targetsUids;
}
public void setTargetsUids(List<String> targetsUids) {
this.targetsUids = targetsUids;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
if (name != null && value != null) {
return String.format("[[%s]:[%s]]", name, value);
}
return super.toString();
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/TaskRunsInfo.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema;
import java.util.List;
public class TaskRunsInfo {
private final String taskRunEnvUid;
private final List<List<String>> parentChildMap;
private final String runUid;
private final List<TaskRun> taskRuns;
private final List<Target> targets;
private final String rootRunUid;
private final List<List<String>> upstreamsMap;
private final boolean dynamicTaskRunUpdate;
private final List<TaskDefinition> taskDefinitions;
private final TrackingSource sourceContext;
public TaskRunsInfo(String taskRunEnvUid,
List<List<String>> parentChildMap,
String runUid,
List<TaskRun> taskRuns,
List<Target> targets,
String rootRunUid,
List<List<String>> upstreamsMap,
boolean dynamicTaskRunUpdate,
List<TaskDefinition> taskDefinitions,
TrackingSource sourceContext) {
this.taskRunEnvUid = taskRunEnvUid;
this.parentChildMap = parentChildMap;
this.runUid = runUid;
this.taskRuns = taskRuns;
this.targets = targets;
this.rootRunUid = rootRunUid;
this.upstreamsMap = upstreamsMap;
this.dynamicTaskRunUpdate = dynamicTaskRunUpdate;
this.taskDefinitions = taskDefinitions;
this.sourceContext = sourceContext;
}
public String getTaskRunEnvUid() {
return taskRunEnvUid;
}
public List<List<String>> getParentChildMap() {
return parentChildMap;
}
public String getRunUid() {
return runUid;
}
public List<TaskRun> getTaskRuns() {
return taskRuns;
}
public List<Target> getTargets() {
return targets;
}
public String getRootRunUid() {
return rootRunUid;
}
public List<List<String>> getUpstreamsMap() {
return upstreamsMap;
}
public boolean isDynamicTaskRunUpdate() {
return dynamicTaskRunUpdate;
}
public List<TaskDefinition> getTaskDefinitions() {
return taskDefinitions;
}
public TrackingSource getSourceContext() {
return sourceContext;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/TaskStates.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema;
public interface TaskStates {
String RUNNING = "running";
String SUCCESS = "success";
String FAILED = "failed";
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/Tasks.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Tasks {
private Map<String, TaskRun> taskInstances;
private List<TargetOperation> targetsOperations;
private Map<String, List<TaskRunAttempt>> attempts;
public Map<String, TaskRun> getTaskInstances() {
return taskInstances;
}
public void setTaskInstances(Map<String, TaskRun> taskInstances) {
this.taskInstances = taskInstances;
}
public List<TargetOperation> getTargetsOperations() {
return targetsOperations;
}
public void setTargetsOperations(List<TargetOperation> targetsOperations) {
this.targetsOperations = targetsOperations;
}
public Map<String, List<TaskRunAttempt>> getAttempts() {
return attempts;
}
public void setAttempts(Map<String, List<TaskRunAttempt>> attempts) {
this.attempts = attempts;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/TasksMetricsRequest.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema;
import java.util.List;
public class TasksMetricsRequest {
private final List<String> uids;
public TasksMetricsRequest(List<String> uids) {
this.uids = uids;
}
public List<String> getUids() {
return uids;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/TasksMetricsResponse.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema;
import java.util.List;
import java.util.Map;
public class TasksMetricsResponse {
private Map<String, Map<String, List<List<Object>>>> metrics;
public Map<String, Map<String, List<List<Object>>>> getMetrics() {
return metrics;
}
public void setMetrics(Map<String, Map<String, List<List<Object>>>> metrics) {
this.metrics = metrics;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/TrackingSource.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema;
public class TrackingSource {
private final String name;
private final String url;
private final String env;
private final String sourceType;
private final String sourceInstanceUid;
/**
* Default constructor.
*
* @param name tracking source name
* @param url tracking source url
* @param env tracking source env
* @param sourceType tracking source type, e.g. "azkaban" or "airflow"
* @param sourceInstanceUid unique tracking source UID
*/
public TrackingSource(String name,
String url,
String env,
String sourceType,
String sourceInstanceUid) {
this.name = name;
this.url = url;
this.env = env;
this.sourceType = sourceType;
this.sourceInstanceUid = sourceInstanceUid;
}
public TrackingSource(AirflowTaskContext airflowTaskContext) {
this(airflowTaskContext.getDagId(),
airflowTaskContext.getAirflowName(),
"airflow",
"airflow",
airflowTaskContext.getAirflowInstanceUid()
);
}
public TrackingSource(AzkabanTaskContext azkabanTaskContext) {
this(azkabanTaskContext.azkabanInstanceId(),
azkabanTaskContext.azkabanUrl(),
"azkaban",
"azkaban",
azkabanTaskContext.azkabanInstanceUuid()
);
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public String getEnv() {
return env;
}
public String getSourceType() {
return sourceType;
}
public String getSourceInstanceUid() {
return sourceInstanceUid;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/UpdateTaskRunAttempts.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema;
import java.util.List;
public class UpdateTaskRunAttempts {
private final List<TaskRunAttemptUpdate> taskRunAttemptUpdates;
public UpdateTaskRunAttempts(List<TaskRunAttemptUpdate> taskRunAttemptUpdates) {
this.taskRunAttemptUpdates = taskRunAttemptUpdates;
}
public List<TaskRunAttemptUpdate> getTaskRunAttemptUpdates() {
return taskRunAttemptUpdates;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/auth/CreateTokenReq.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.auth;
import java.util.UUID;
public class CreateTokenReq {
private final String label;
private final String lifespan;
public CreateTokenReq() {
this(UUID.randomUUID().toString(), "3600");
}
public CreateTokenReq(String label, String lifespan) {
this.label = label;
this.lifespan = lifespan;
}
public String getLabel() {
return label;
}
public String getLifespan() {
return lifespan;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/auth/CreateTokenRes.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.auth;
public class CreateTokenRes {
private String uid;
private String token;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/auth/LoginReq.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.auth;
import java.util.Optional;
public class LoginReq {
private final String username;
private final String password;
public LoginReq() {
this.username = Optional.ofNullable(System.getenv("DBND__TRACKER__USERNAME")).orElse("databand");
this.password = Optional.ofNullable(System.getenv("DBND__TRACKER__PASSWORD")).orElse("databand");
}
public LoginReq(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/auth/LoginRes.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.auth;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class LoginRes {
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/histograms/ColumnSummary.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.histograms;
import java.util.HashMap;
import java.util.Map;
public class ColumnSummary implements Summary {
private final long count;
private final long distinct;
private final long nonNull;
private final long nullCount;
private final String type;
public ColumnSummary(long count, long distinct, long nonNull, long nullCount, String type) {
this.count = count;
this.distinct = distinct;
this.nonNull = nonNull;
this.nullCount = nullCount;
this.type = type;
}
public long getCount() {
return count;
}
public long getDistinct() {
return distinct;
}
public long getNonNull() {
return nonNull;
}
public long getNullCount() {
return nullCount;
}
public String getType() {
return type;
}
public Map<String, Object> toMap() {
Map<String, Object> result = new HashMap<>(5);
result.put("count", count);
result.put("distinct", distinct);
result.put("non-null", nonNull);
result.put("null-count", nullCount);
result.put("type", type);
return result;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/histograms/NumericSummary.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.histograms;
import java.util.HashMap;
import java.util.Map;
public class NumericSummary implements Summary {
private final ColumnSummary columnSummary;
private final double max;
private final double mean;
private final double min;
private final double stddev;
private final double _25;
private final double _50;
private final double _75;
public NumericSummary(ColumnSummary columnSummary,
double max,
double mean,
double min,
double stddev,
double _25,
double _50,
double _75) {
this.columnSummary = columnSummary;
this.max = max;
this.mean = mean;
this.min = min;
this.stddev = stddev;
this._25 = _25;
this._50 = _50;
this._75 = _75;
}
public long getCount() {
return columnSummary.getCount();
}
public long getDistinct() {
return columnSummary.getDistinct();
}
public long getNonNull() {
return columnSummary.getNonNull();
}
public long getNullCount() {
return columnSummary.getNullCount();
}
public String getType() {
return columnSummary.getType();
}
public double getMax() {
return max;
}
public double getMean() {
return mean;
}
public double getMin() {
return min;
}
public double getStd() {
return stddev;
}
public double getStddev() {
return stddev;
}
public double get_25() {
return _25;
}
public double get_50() {
return _50;
}
public double get_75() {
return _75;
}
public Map<String, Object> toMap() {
Map<String, Object> result = new HashMap<>(12);
result.put("max", max);
result.put("mean", mean);
result.put("min", min);
result.put("stddev", stddev);
result.put("std", stddev);
result.put("25%", _25);
result.put("50%", _50);
result.put("75%", _75);
result.putAll(columnSummary.toMap());
return result;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/histograms/Summary.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.histograms;
import java.util.Map;
public interface Summary {
long getCount();
long getDistinct();
long getNonNull();
long getNullCount();
String getType();
Map<String, Object> toMap();
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/jackson/LocalDateDeserializer.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.jackson;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class LocalDateDeserializer extends StdDeserializer<LocalDate> {
private final String PATTERN = "yyyy-MM-dd";
private final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(PATTERN);
public LocalDateDeserializer() {
this(null);
}
public LocalDateDeserializer(Class<LocalDate> t) {
super(t);
}
@Override
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.getValueAsString();
return LocalDate.parse(value, FORMATTER);
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/jackson/LocalDateSerializer.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.jackson;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class LocalDateSerializer extends StdSerializer<LocalDate> {
private final String PATTERN = "yyyy-MM-dd";
private final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(PATTERN);
public LocalDateSerializer() {
this(null);
}
public LocalDateSerializer(Class<LocalDate> t) {
super(t);
}
@Override
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeString(value.format(FORMATTER));
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/jackson/ZonedDateTimeDeserializer.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.jackson;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME;
public class ZonedDateTimeDeserializer extends StdDeserializer<ZonedDateTime> {
private final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX";
private final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(PATTERN);
public ZonedDateTimeDeserializer() {
this(null);
}
public ZonedDateTimeDeserializer(Class<ZonedDateTime> t) {
super(t);
}
@Override
public ZonedDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = p.getValueAsString();
try {
return ZonedDateTime.parse(value, FORMATTER);
} catch (Exception e) {
return ZonedDateTime.parse(value, ISO_OFFSET_DATE_TIME);
}
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/jackson/ZonedDateTimeSerializer.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.jackson;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class ZonedDateTimeSerializer extends StdSerializer<ZonedDateTime> {
private static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX";
public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(PATTERN);
public ZonedDateTimeSerializer() {
this(null);
}
public ZonedDateTimeSerializer(Class<ZonedDateTime> t) {
super(t);
}
@Override
public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeString(value.format(FORMATTER));
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/schema/tasks/GetTasksReq.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.schema.tasks;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class GetTasksReq {
@JsonProperty("uids")
private List<String> taskUids;
public GetTasksReq(List<String> taskUids) {
this.taskUids = taskUids;
}
public List<String> getTaskUids() {
return taskUids;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/spark/ActiveJobTracker.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.spark;
import ai.databand.DbndWrapper;
import org.apache.spark.Dependency;
import org.apache.spark.rdd.RDD;
import org.apache.spark.scheduler.ActiveJob;
import org.apache.spark.scheduler.Stage;
import org.apache.spark.sql.execution.datasources.FilePartition;
import org.apache.spark.sql.execution.datasources.FileScanRDD;
import org.apache.spark.sql.execution.datasources.PartitionedFile;
import org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions;
import org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD;
import scala.collection.Iterator;
import java.lang.reflect.Field;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.stream.Collectors;
public class ActiveJobTracker {
/**
* Extract IO information from Spark ActiveJob.
*
* @param job Spark job
*/
public static void track(ActiveJob job) {
Stage stage = job.finalStage();
List<RDD<?>> all = allRdds(stage.rdd());
List<SparkIOSource> sources = new ArrayList<>(1);
for (RDD<?> rdd : all) {
if (rdd instanceof FileScanRDD) {
FileScanRDD fs = (FileScanRDD) rdd;
Iterator<FilePartition> iterator = fs.filePartitions().iterator();
while (iterator.hasNext()) {
FilePartition filePart = iterator.next();
for (PartitionedFile file : filePart.files()) {
Map<String, Object> properties = new HashMap<>(1);
properties.put("start", file.start());
properties.put("length", file.length());
properties.put("index", filePart.index());
sources.add(new SparkIOSource(file.filePath(), "file_scan_rdd", properties));
}
}
} else if (rdd instanceof JDBCRDD) {
JDBCRDD db = (JDBCRDD) rdd;
Optional<SparkIOSource> dbSource = extractDataFromJdbcRdd(db);
dbSource.ifPresent(sources::add);
}
}
// TODO: Track Snowflake RDD
Map<String, Object> metrics = sources.stream().collect(Collectors.toMap(SparkIOSource::metricKey, io -> io));
DbndWrapper.instance().logMetrics(metrics, "spark");
}
public static Optional<SparkIOSource> extractDataFromJdbcRdd(JDBCRDD rdd) {
try {
Field optionsField = rdd.getClass().getDeclaredField("options");
optionsField.setAccessible(true);
Field columnListField = rdd.getClass().getDeclaredField("columnList");
columnListField.setAccessible(true);
JDBCOptions options = (JDBCOptions) optionsField.get(rdd);
String columnsList = (String) columnListField.get(rdd);
Map<String, Object> properties = new HashMap<>(2);
Map<String, Object> jdbcOptions = new HashMap<>(2);
jdbcOptions.put("url", options.url());
jdbcOptions.put("table_or_query", options.tableOrQuery());
properties.put("options", jdbcOptions);
properties.put("columnsList", columnsList);
return Optional.of(new SparkIOSource(options.url(), "jdbc_rdd", properties));
} catch (NoSuchFieldException | IllegalAccessException e) {
return Optional.empty();
}
}
/**
* Recursively extract all rdds from job.
*
* @param rdd top-level rdd
* @return list of all downstream rdds
*/
public static List<RDD<?>> allRdds(RDD<?> rdd) {
List<RDD<?>> result = new ArrayList<>(1);
Queue<RDD<?>> stack = new ArrayDeque<>(Collections.singletonList(rdd));
while (!stack.isEmpty()) {
RDD<?> polled = stack.poll();
result.add(polled);
for (scala.collection.Iterator<Dependency<?>> it = polled.dependencies().iterator(); it.hasNext(); ) {
Dependency<?> next = it.next();
stack.add(next.rdd());
}
}
return result;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/spark/DbndSparkListener.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022-2024
*/
package ai.databand.spark;
import ai.databand.DbndAppLog;
import ai.databand.DbndWrapper;
import ai.databand.config.DbndConfig;
import org.apache.spark.scheduler.SparkListener;
import org.apache.spark.scheduler.SparkListenerEvent;
import org.apache.spark.scheduler.SparkListenerJobStart;
import org.apache.spark.scheduler.SparkListenerStageCompleted;
import org.apache.spark.sql.execution.SparkPlanInfo;
import org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionStart;
import org.slf4j.LoggerFactory;
import scala.Tuple2;
import scala.collection.Iterator;
/**
* Spark listener to report all spark-generated metrics for stages to Databand.
* This class is safe to use in any circumstances and won't break client code.
*/
public class DbndSparkListener extends SparkListener {
private static final DbndAppLog LOG = new DbndAppLog(LoggerFactory.getLogger(DbndSparkListener.class));
private final DbndWrapper dbnd;
public DbndSparkListener(DbndWrapper dbnd) {
this.dbnd = dbnd;
LOG.jvmInfo("Succesfully constructed Databand Listener instance. Selected Spark properties and metrics will be submitted to the Databand service.");
}
public DbndSparkListener() {
this.dbnd = DbndWrapper.instance();
LOG.jvmInfo("Succesfully constructed Databand Listener instance. Selected Spark properties and metrics will be submitted to the Databand service.");
}
/*@Override
public void onOtherEvent(SparkListenerEvent event) {
if (event instanceof SparkListenerSQLExecutionStart) {
SparkListenerSQLExecutionStart sqlEvent = (SparkListenerSQLExecutionStart) event;
// QueryExecution queryExecution = SQLExecution.getQueryExecution(sqlEvent.executionId());
// SQL query info will be extracted by SQL Query Listener
//extractIoInfo(sqlEvent.sparkPlanInfo());
}
}*/
/**
* input location path
* read schema
* data format
*
* @param plan
*/
protected void extractIoInfo(SparkPlanInfo plan) {
Iterator<Tuple2<String, String>> iterator = plan.metadata().iterator();
while (iterator.hasNext()) {
Tuple2<String, String> next = iterator.next();
if ("Location".equalsIgnoreCase(next._1())) {
SparkIOSource source = new SparkIOSource(next._2(), "spark_plan_info");
dbnd.logMetric(source.metricKey(), source);
}
}
for (Iterator<SparkPlanInfo> it = plan.children().iterator(); it.hasNext(); ) {
extractIoInfo(it.next());
}
}
@Override
public void onJobStart(SparkListenerJobStart jobStart) {
try {
DbndConfig conf = dbnd.config();
conf.setSparkProperties(jobStart.properties());
} catch (Throwable e) {
LOG.error("Failed to set Spark properties during onJobStart() handling: {}", e);
}
}
/*@Override
public void onStageCompleted(SparkListenerStageCompleted stageCompleted) {
try {
dbnd.logSpark(stageCompleted);
} catch (Throwable e) {
System.out.println("DbndSparkListener: Unable to log spark metrics");
e.printStackTrace();
}
}*/
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/spark/DbndSparkQueryExecutionListener.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022-2024
*/
package ai.databand.spark;
import static ai.databand.DbndPropertyNames.DBND_INTERNAL_ALIAS;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.spark.sql.catalyst.plans.QueryPlan;
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan;
import org.apache.spark.sql.execution.CollectLimitExec;
import org.apache.spark.sql.execution.FileSourceScanExec;
import org.apache.spark.sql.execution.QueryExecution;
import org.apache.spark.sql.execution.SparkPlan;
import org.apache.spark.sql.execution.WholeStageCodegenExec;
import org.apache.spark.sql.execution.command.DataWritingCommandExec;
import org.apache.spark.sql.execution.datasources.HadoopFsRelation;
import org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand;
import org.apache.spark.sql.execution.metric.SQLMetric;
import org.apache.spark.sql.hive.execution.HiveTableScanExec;
import org.apache.spark.sql.hive.execution.InsertIntoHiveTable;
import org.apache.spark.sql.types.StructType;
import org.apache.spark.sql.util.QueryExecutionListener;
import org.slf4j.LoggerFactory;
import ai.databand.DbndAppLog;
import ai.databand.DbndWrapper;
import ai.databand.parameters.DatasetOperationPreview;
import ai.databand.schema.ColumnStats;
import ai.databand.schema.DatasetOperationStatus;
import ai.databand.schema.DatasetOperationType;
import ai.databand.schema.LogDataset;
import ai.databand.schema.Pair;
import scala.collection.Map;
public class DbndSparkQueryExecutionListener implements QueryExecutionListener {
private static final DbndAppLog LOG = new DbndAppLog(LoggerFactory.getLogger(DbndSparkQueryExecutionListener.class));
private final DbndWrapper dbnd;
private final DatasetOperationPreview operationPreview;
private final boolean isHiveEnabled;
public DbndSparkQueryExecutionListener(DbndWrapper dbnd) {
this.dbnd = dbnd;
this.operationPreview = new DatasetOperationPreview();
// test if Hive is installed on cluster to avoid ClassNotFoundException in runtime
try {
Class.forName("org.apache.spark.sql.hive.execution.HiveTableScanExec", false, getClass().getClassLoader());
Class.forName("org.apache.spark.sql.hive.execution.InsertIntoHiveTable", false, getClass().getClassLoader());
} catch (ClassNotFoundException e) {
isHiveEnabled = false;
return;
}
isHiveEnabled = true;
LOG.jvmInfo("Succesfully constructed Databand QueryExecutionListener instance. Selected Spark events with dataset operations will be submitted to the Databand service.");
}
public DbndSparkQueryExecutionListener() {
this(DbndWrapper.instance());
}
@Override
public void onSuccess(String funcName, QueryExecution qe, long durationNs) {
boolean isProcessed = false;
SparkPlan rootPlan = qe.executedPlan();
LOG.verbose("[{}] Processing event from function \"{}()\" and execution plan class: {}. Executed root plan: {}", rootPlan.hashCode(), funcName, rootPlan.getClass().getName(), rootPlan);
// Instanceof chain used instead of pattern-matching for the sake of simplicity here.
// When new implementations will be added, this part should be refactored to use pattern-matching (strategies)
if (isAdaptivePlan(rootPlan)) {
rootPlan = extractFinalFromAdaptive(rootPlan).orElse(rootPlan);
LOG.verbose("[{}] Extracted final root plan from adaptive plan. Final executed root plan: {}", rootPlan.hashCode(), rootPlan);
}
if (rootPlan instanceof DataWritingCommandExec) {
LOG.verbose("[{}] rootPlan is instanceof DataWritingCommandExec", rootPlan.hashCode());
isProcessed = submitReadWriteOps(rootPlan);
}
if (rootPlan instanceof WholeStageCodegenExec) {
LOG.verbose("[{}] rootPlan is instanceof WholeStageCodegenExec", rootPlan.hashCode());
if (isDbndPlan(qe)) {
LOG.warn("[{}] Explicit Databand SDK DataFrame tracking will not be reported by JVM", rootPlan.hashCode());
return;
}
isProcessed = submitReadWriteOps(rootPlan);
}
if (rootPlan.getClass().getName().equals("org.apache.spark.sql.execution.adaptive.ResultQueryStageExec")) {
// Databricks Spark
LOG.verbose("[{}] rootPlan is instanceof ResultQueryStageExec", rootPlan.hashCode());
isProcessed = submitReadWriteOps(rootPlan);
}
/* It might need to be enabled if used by some customers (SQLs with "limit X" statement)
if (rootPlan instanceof CollectLimitExec) {
LOG.verbose("[{}] rootPlan is instanceof CollectLimitExec", rootPlan.hashCode());
isProcessed = submitReadWriteOps(rootPlan);
}*/
if (!isProcessed) {
LOG.verbose("[{}] Spark event was not processed because root execution plan class {} and all its child plans are not supported", rootPlan.hashCode(), rootPlan.getClass().getName());
} else {
LOG.verbose("[{}] Spark event was processed succesfully, root execution plan class: {}", rootPlan.hashCode(), rootPlan.getClass().getName());
}
}
protected boolean submitReadWriteOps(SparkPlan rootPlan) {
boolean isProcessed = false;
List<SparkPlan> allChildren = getAllChildren(rootPlan);
LOG.verbose("[{}] {} children plans detected.", rootPlan.hashCode(), allChildren.size());
for (SparkPlan next : allChildren) {
if (next instanceof FileSourceScanExec) {
LOG.verbose("[{}][{}] Supported FileSourceScanExec child plan type detected", rootPlan.hashCode(), next.hashCode());
FileSourceScanExec fileSourceScan = (FileSourceScanExec) next;
StructType schema = fileSourceScan.schema();
// when performing operations like "count" schema is not reported in a FileSourceScanExec itself,
// but we can try to figure it out from the HadoopRelation.
if (schema.isEmpty() && fileSourceScan.relation() != null) {
schema = fileSourceScan.relation().schema();
}
String path = extractPath(fileSourceScan.metadata().get("Location").get());
long rows = fileSourceScan.metrics().get("numOutputRows").get().value();
log(path, DatasetOperationType.READ, schema, rows,false);
isProcessed = true;
continue;
}
if (next.getClass().getName().equals("com.databricks.photon.PhotonJsonFileScanExec")) {
// Databricks Spark Photon engine
LOG.verbose("[{}][{}] Supported PhotonJsonFileScanExec child plan type detected", rootPlan.hashCode(), next.hashCode());
try {
Class[] argTypes = new Class[] {};
Method mschema = next.getClass().getMethod("schema", argTypes);
StructType schema = (StructType) mschema.invoke(next);
// when performing operations like "count" schema is not reported in a PhotonJsonFileScanExec itself,
// but we can try to figure it out from the HadoopRelation.
if (schema.isEmpty()) {
Method mrelation = next.getClass().getMethod("relation", argTypes);
HadoopFsRelation relation = (HadoopFsRelation) mrelation.invoke(next);
if (relation != null) {
schema = relation.schema();
}
}
Method mmetadata = next.getClass().getMethod("metadata", argTypes);
Map<String, String> meta = (Map<String, String>) mmetadata.invoke(next);
String path = extractPath(meta.get("Location").get());
Method mmetrics = next.getClass().getMethod("metrics", argTypes);
Map<String, SQLMetric> metrics = (Map<String, SQLMetric>) mmetrics.invoke(next);
long rows = metrics.get("numOutputRows").get().value();
log(path, DatasetOperationType.READ, schema, rows,false);
isProcessed = true;
} catch (Exception e) {
LOG.error("[{}][{}] Unable to extract dataset information from PhotonJsonFileScanExec - {}", rootPlan.hashCode(), next.hashCode(), e);
}
continue;
}
if (isHiveEnabled) {
if (next instanceof HiveTableScanExec) {
LOG.verbose("[{}][{}] Supported HiveTableScanExec child plan type detected", rootPlan.hashCode(), next.hashCode());
try {
HiveTableScanExec hiveTableScan = (HiveTableScanExec) next;
// Hive Table name, may be reused in future
// String tableName = hiveTableScan.relation().tableMeta().identifier().table();
// Path resolved by Hive Metastore
String path = hiveTableScan.relation().tableMeta().storage().locationUri().get().toString();
long rows = hiveTableScan.metrics().get("numOutputRows").get().value();
log(path, DatasetOperationType.READ, hiveTableScan.relation().schema(), rows,true);
isProcessed = true;
} catch (Exception e) {
LOG.error("[{}][{}] Unable to extract dataset information from HiveTableScanExec - {}", rootPlan.hashCode(), next.hashCode(), e);
}
continue;
}
}
if (next instanceof DataWritingCommandExec) {
LOG.verbose("[{}][{}] Supported DataWritingCommandExec child plan type detected", rootPlan.hashCode(), next.hashCode());
DataWritingCommandExec writePlan = (DataWritingCommandExec) next;
if (writePlan.cmd() instanceof InsertIntoHadoopFsRelationCommand) {
LOG.verbose("[{}][{}] writeplan is instanceof InsertIntoHadoopFsRelationCommand", rootPlan.hashCode(), writePlan.hashCode());
InsertIntoHadoopFsRelationCommand cmd = (InsertIntoHadoopFsRelationCommand) writePlan.cmd();
String path = extractPath(cmd.outputPath().toString());
long rows = cmd.metrics().get("numOutputRows").get().value();
log(path, DatasetOperationType.WRITE, cmd.query().schema(), rows,false);
isProcessed = true;
}
if (isHiveEnabled) {
if (writePlan.cmd() instanceof InsertIntoHiveTable) {
LOG.verbose("[{}][{}] writeplan is instanceof InsertIntoHiveTable", rootPlan.hashCode(), writePlan.hashCode());
try {
InsertIntoHiveTable cmd = (InsertIntoHiveTable) writePlan.cmd();
String path = cmd.table().identifier().table();
long rows = cmd.metrics().get("numOutputRows").get().value();
log(path, DatasetOperationType.WRITE, cmd.query().schema(), rows,true);
isProcessed = true;
} catch (Exception e) {
LOG.error("[{}][{}] Unable to extract dataset information from InsertIntoHiveTable - {}", rootPlan.hashCode(), writePlan.hashCode(), e);
}
}
}
continue;
}
LOG.verbose("[{}][{}] Unsupported children plan: {}", rootPlan.hashCode(), next.hashCode(), next.getClass().getName());
}
return isProcessed;
}
private boolean isDbndPlan(QueryExecution qe) {
if (qe.analyzed() != null && !qe.analyzed().children().isEmpty()) {
String dfAlias = getPlanVerboseString(qe.analyzed().children().apply(0));
return dfAlias != null && dfAlias.contains(DBND_INTERNAL_ALIAS);
}
return false;
}
protected boolean isAdaptivePlan(Object plan) {
return plan.getClass().getName().contains("AdaptiveSparkPlanExec");
}
/**
* This is workaround for Spark 3.
* verboseString() method was replaced in Spark 3 by verboseString(int).
*
* @param plan
* @return
*/
protected String getPlanVerboseString(LogicalPlan plan) {
try {
return plan.verboseString();
} catch (NoSuchMethodError e) {
// we're in spark 3
try {
Class<?> clazz = QueryPlan.class;
Method method = clazz.getDeclaredMethod("verboseString", int.class);
return method.invoke(plan, 1).toString();
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
LOG.error("Unable to identify whenever spark query was triggered by log_dataset_op or not", ex);
return null;
}
}
}
/**
* Adaptive plans was introduced in Spark 2.4.8+ and turned on by default on some configurations.
* For proper reporting we use reflection to extract relevant pieces from Adaptive Plans.
* Reflection allows us to avoid direct dependency bump.
*
* @param adaptivePlan
* @return
*/
protected Optional<SparkPlan> extractFinalFromAdaptive(SparkPlan adaptivePlan) {
try {
Class<?> clazz = Class.forName("org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanExec");
Field field = clazz.getDeclaredField("currentPhysicalPlan");
field.setAccessible(true);
SparkPlan value = (SparkPlan) field.get(adaptivePlan);
return Optional.of(value);
} catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
LOG.error("[{}] Unable to extract final plan from the adaptive one using reflection. Dataset operation won't be logged - {}.", adaptivePlan.hashCode(), e);
return Optional.empty();
}
}
protected void log(String path, DatasetOperationType operationType, StructType datasetSchema, long rows,boolean isPartitioned) {
Pair<String, List<Long>> schema = operationPreview.extractSchema(datasetSchema, rows);
List<ColumnStats> columnStats = operationPreview.extractColumnStats(datasetSchema, rows);
dbnd.logDatasetOperation(
path,
operationType,
DatasetOperationStatus.OK,
"",
schema.right(),
schema.left(),
isPartitioned,
columnStats,
LogDataset.OP_SOURCE_SPARK_QUERY_LISTENER
);
}
private final Pattern DATASET = Pattern.compile(".*\\[(.*)\\].*");
/**
* Extract data path from spark query plan.
*
* @param path
* @return
*/
protected String extractPath(String path) {
Matcher matcher = DATASET.matcher(path);
if (matcher.matches()) {
return matcher.group(1);
}
return path;
}
/**
* DFS across spark plan nodes.
*
* @param root
* @return
*/
protected List<SparkPlan> getAllChildren(SparkPlan root) {
List<SparkPlan> result = new ArrayList<>();
Deque<SparkPlan> deque = new LinkedList<>();
deque.add(root);
List<String> spark3classes = Arrays.asList("org.apache.spark.sql.execution.adaptive.ShuffleQueryStageExec", "org.apache.spark.sql.execution.adaptive.BroadcastQueryStageExec", "org.apache.spark.sql.execution.adaptive.ResultQueryStageExec");
while (!deque.isEmpty()) {
SparkPlan next = deque.pop();
result.add(next);
if (spark3classes.contains(next.getClass().getName())) {
// Spark 3 feature
Optional<SparkPlan> spark3Child = extractChildFromSpark3(next);
spark3Child.ifPresent(deque::add);
if(!spark3Child.isPresent()) {
LOG.verbose("[{}][{}] No child node for Spark3 node class '{}'", root.hashCode(), next.hashCode(), next.getClass().getName());
}
} else if (next.getClass().getName().contains("AdaptiveSparkPlanExec")) {
Optional<SparkPlan> finalPlanFromAdaptive = extractFinalFromAdaptive(next);
finalPlanFromAdaptive.ifPresent(deque::add);
} else {
List<SparkPlan> children = scala.collection.JavaConverters.seqAsJavaListConverter(next.children()).asJava();
deque.addAll(children);
if(children.size() == 0) {
// For some Spark nodes this message means new node type needs to be added to "spark3classes" list
LOG.verbose("[{}][{}] No children nodes for node '{}'", root.hashCode(), next.hashCode(), next.getClass().getName());
}
}
}
return result;
}
/**
* Some queries were introduced in Spark 3 and doesn't have "children" nodes.
* Instead, the child node can be accessed using plan() method.
* We use reflection to gain access to this method in runtime and avoid direct dependency to Spark 3.
*
* @param spark3Query
* @return
*/
protected Optional<SparkPlan> extractChildFromSpark3(SparkPlan spark3Query) {
try {
Class<?> clazz = Class.forName(spark3Query.getClass().getName());
Method method = clazz.getDeclaredMethod("plan");
SparkPlan value = (SparkPlan) method.invoke(spark3Query);
return Optional.of(value);
} catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException |
InvocationTargetException e) {
LOG.error("[{}] Unable to extract child plan from the spark3 query '{}' using reflection. Dataset operation won't be logged - {}.", spark3Query.hashCode(), spark3Query.getClass().getName(), e);
return Optional.empty();
}
}
@Override
public void onFailure(String funcName, QueryExecution qe, Exception exception) {
// not implemented yet
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/spark/SparkColumnStats.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.spark;
import ai.databand.log.HistogramRequest;
import ai.databand.log.LogDatasetRequest;
import ai.databand.parameters.Histogram;
import ai.databand.schema.ColumnStats;
import ai.databand.schema.histograms.NumericSummary;
import ai.databand.schema.histograms.Summary;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.types.StructField;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static ai.databand.DbndPropertyNames.DBND_INTERNAL_ALIAS;
public class SparkColumnStats {
private final Dataset<?> dataset;
private final LogDatasetRequest params;
public SparkColumnStats(Dataset<?> dataset, LogDatasetRequest params) {
this.dataset = dataset.alias(String.format("%s_%s", DBND_INTERNAL_ALIAS, "COLUMN_STATS"));
this.params = params;
}
public List<ColumnStats> values() {
if (!params.getWithStats()) {
return Collections.emptyList();
}
Histogram histogram = new Histogram("columnStat", dataset, new HistogramRequest().onlyStats());
Map<String, String> columnTypes = new HashMap<>();
for (StructField field : dataset.schema().fields()) {
columnTypes.put(field.name(), field.dataType().typeName());
}
// calculate summary
histogram.summary();
Map<String, Summary> summaries = histogram.getSummaries();
List<ColumnStats> result = new ArrayList<>(summaries.size());
for (Map.Entry<String, Summary> col : summaries.entrySet()) {
Summary columnMetrics = col.getValue();
ColumnStats columnStats = new ColumnStats()
.setColumnName(col.getKey())
.setColumnType(columnTypes.get(col.getKey()))
.setRecordsCount(columnMetrics.getCount())
.setDistinctCount(columnMetrics.getDistinct());
if (columnMetrics instanceof NumericSummary) {
NumericSummary numericSummary = (NumericSummary) columnMetrics;
columnStats.setMeanValue(numericSummary.getMean())
.setMinValue(numericSummary.getMin())
.setMaxValue(numericSummary.getMax())
.setStdValue(numericSummary.getStd())
.setQuartile1(numericSummary.get_25())
.setQuartile2(numericSummary.get_50())
.setQuartile3(numericSummary.get_75());
}
result.add(columnStats);
}
return result;
}
}
|
0
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-client/1.0.28.1/ai/databand/spark/SparkIOSource.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.spark;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
public class SparkIOSource {
private static final Logger LOG = LoggerFactory.getLogger(SparkIOSource.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private final String path;
private final Map<String, Object> properties;
private final String metricKey;
private final String trackingSource;
public SparkIOSource(String path, String trackingSource, Map<String, Object> properties) {
this.path = path;
this.trackingSource = trackingSource;
this.properties = properties;
this.metricKey = "spark-io-" + UUID.randomUUID();
}
public SparkIOSource(String path, String trackingSource) {
this(path, trackingSource, Collections.emptyMap());
}
public String getPath() {
return path;
}
public String getTrackingSource() {
return trackingSource;
}
@JsonIgnore
public String metricKey() {
return metricKey;
}
public Map<String, Object> getProperties() {
return properties;
}
public String toString() {
try {
return MAPPER.writeValueAsString(this);
} catch (JsonProcessingException e) {
LOG.error("Unable to serialize Spark IO source", e);
return "{}";
}
}
}
|
0
|
java-sources/ai/databand/dbnd-deequ/0.40.2/ai/databand
|
java-sources/ai/databand/dbnd-deequ/0.40.2/ai/databand/deequ/DbndMetricsRepository.java
|
package ai.databand.deequ;
import ai.databand.DbndWrapper;
import com.amazon.deequ.analyzers.runners.AnalyzerContext;
import com.amazon.deequ.repository.MetricsRepository;
import com.amazon.deequ.repository.MetricsRepositoryMultipleResultsLoader;
import com.amazon.deequ.repository.ResultKey;
import scala.Option;
import scala.collection.JavaConverters;
import java.util.Map;
/**
* Deequ metrics repository implementation. Reports all Deequ metrics to Databand.
*/
public class DbndMetricsRepository implements MetricsRepository {
private final DbndWrapper dbnd;
private final MetricsRepository origin;
public DbndMetricsRepository(DbndWrapper dbnd) {
this.dbnd = dbnd;
this.origin = new NoopMetricsRepository();
}
public DbndMetricsRepository(DbndWrapper dbnd, MetricsRepository originRepo) {
this.dbnd = dbnd;
this.origin = originRepo;
}
public DbndMetricsRepository() {
this.dbnd = DbndWrapper.instance();
this.origin = new NoopMetricsRepository();
}
public DbndMetricsRepository(MetricsRepository originRepo) {
this.dbnd = DbndWrapper.instance();
this.origin = originRepo;
}
@Override
public void save(ResultKey resultKey, AnalyzerContext analyzerContext) {
origin.save(resultKey, analyzerContext);
String dfName;
if (resultKey instanceof DbndResultKey) {
dfName = ((DbndResultKey) resultKey).dataSetName();
} else {
Map<String, String> tags = JavaConverters.mapAsJavaMapConverter(resultKey.tags()).asJava();
dfName = tags.getOrDefault("name", "data");
}
DeequToDbnd converted = new DeequToDbnd(dfName, analyzerContext);
dbnd.logMetrics(converted.metrics());
dbnd.logHistogram(converted.histograms());
}
@Override
public Option<AnalyzerContext> loadByKey(ResultKey resultKey) {
return origin.loadByKey(resultKey);
}
@Override
public MetricsRepositoryMultipleResultsLoader load() {
return origin.load();
}
}
|
0
|
java-sources/ai/databand/dbnd-deequ/0.40.2/ai/databand
|
java-sources/ai/databand/dbnd-deequ/0.40.2/ai/databand/deequ/DbndResultKey.java
|
package ai.databand.deequ;
import com.amazon.deequ.repository.ResultKey;
import scala.collection.immutable.Map;
public class DbndResultKey extends ResultKey {
private final String dataSetName;
public DbndResultKey(long dataSetDate, Map<String, String> tags, String dataSetName) {
super(dataSetDate, tags);
this.dataSetName = dataSetName;
}
public DbndResultKey(String dataSetName) {
super(System.currentTimeMillis(), scala.collection.immutable.Map$.MODULE$.<String, String>empty());
this.dataSetName = dataSetName;
}
public DbndResultKey(long dataSetDate, Map<String, String> tags) {
super(dataSetDate, tags);
this.dataSetName = "dataSet";
}
public String dataSetName() {
return dataSetName;
}
}
|
0
|
java-sources/ai/databand/dbnd-deequ/0.40.2/ai/databand
|
java-sources/ai/databand/dbnd-deequ/0.40.2/ai/databand/deequ/DeequToDbnd.java
|
package ai.databand.deequ;
import com.amazon.deequ.analyzers.runners.AnalyzerContext;
import com.amazon.deequ.metrics.Distribution;
import com.amazon.deequ.metrics.DistributionValue;
import com.amazon.deequ.metrics.Metric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.collection.JavaConverters;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class DeequToDbnd {
private static final Logger LOG = LoggerFactory.getLogger(DeequToDbnd.class);
private final String dfName;
private final List<Metric<?>> deequMetrics;
private static final Map<String, String> DEEQU_TO_SPARK = new HashMap<>();
static {
DEEQU_TO_SPARK.put("ApproxCountDistinct", "distinct");
DEEQU_TO_SPARK.put("Minimum", "min");
DEEQU_TO_SPARK.put("Maximum", "max");
DEEQU_TO_SPARK.put("Mean", "mean");
DEEQU_TO_SPARK.put("StandardDeviation", "stddev");
DEEQU_TO_SPARK.put("Histogram", "histogram");
}
private static final Map<String, String> DEEQU_TO_DBND = new HashMap<>();
static {
DEEQU_TO_DBND.put("Boolean", "boolean");
DEEQU_TO_DBND.put("Fractional", "double");
DEEQU_TO_DBND.put("Integral", "integer");
DEEQU_TO_DBND.put("String", "string");
DEEQU_TO_DBND.put("Unknown", "string");
}
public DeequToDbnd(String dfName, AnalyzerContext analyzerContext) {
this.dfName = dfName;
deequMetrics = JavaConverters.seqAsJavaListConverter(analyzerContext.metricMap().values().toSeq()).asJava();
}
public Map<String, Object> metrics() {
Map<String, Object> metrics = new HashMap<>(1);
for (Metric<?> m : deequMetrics) {
// skip histogram metrics
if (m.value().isSuccess() && m.value().get() instanceof Distribution) {
continue;
}
String metricKey = String.format("deequ.%s.%s.%s", dfName, m.instance(), m.name());
if (m.value().isFailure()) {
LOG.error("Deequ calculation failed for key [{}]. Reason: {}", metricKey, m.value().failed().get().getMessage());
}
Object value = m.value().isSuccess() ? m.value().get() : "Failure";
metrics.put(metricKey, value);
}
return metrics;
}
public Map<String, Object> histograms() {
return buildHistograms(dfName, deequMetrics);
}
public Map<String, Object> buildHistograms(String dfName, List<Metric<?>> deequMetrics) {
Set<String> histogrammedCols = deequMetrics.stream()
.filter(m -> "Histogram".equalsIgnoreCase(m.name()))
.map(Metric::instance)
.collect(Collectors.toSet());
if (histogrammedCols.isEmpty()) {
return Collections.emptyMap();
}
Map<String, Object> result = new HashMap<>(1);
Map<String, Object> histograms = new HashMap<>(1);
Map<String, Map<String, Object>> stats = histogrammedCols.stream().collect(Collectors.toMap((m) -> m, (m) -> new HashMap<>(1)));
for (Metric<?> m : deequMetrics) {
String col = m.instance();
if (!histogrammedCols.contains(col)) {
continue;
}
String sparkMetric = DEEQU_TO_SPARK.get(m.name());
if (sparkMetric == null) {
continue;
}
if ("histogram".equalsIgnoreCase(sparkMetric)) {
// check we have real histogram
Distribution distribution = (Distribution) m.value().get();
Map<String, DistributionValue> binsAndValues = JavaConverters.mapAsJavaMapConverter(distribution.values()).asJava();
if (isDistributionHistogram(binsAndValues)) {
// this is values distribution. Let's calculate column type based on this information
String type = guessColumnTypeByDistribution(binsAndValues);
stats.get(col).put("type", type);
continue;
}
Object[][] histogram = distributionToHistogram(binsAndValues);
histograms.put(col, histogram);
// let's guess column type
// TODO: optimize
if (!stats.get(col).containsKey("type")) {
Object[] bins = histogram[1];
if (allBooleans(bins)) {
stats.get(col).put("type", "boolean");
} else if (allIntegers(bins)) {
stats.get(col).put("type", "integer");
} else if (allDoubles(bins)) {
stats.get(col).put("type", "double");
} else {
stats.get(col).put("type", "string");
}
}
continue;
}
stats.get(col).put(sparkMetric, m.value().get());
result.put(String.format("%s.%s.%s", dfName, col, sparkMetric), m.value().get());
}
result.put(String.format("%s.stats", dfName), stats);
if (!histograms.isEmpty()) {
result.put(String.format("%s.histograms", dfName), histograms);
}
return result;
}
public Object[][] distributionToHistogram(Map<String, DistributionValue> binsAndValues) {
Object[] bins = new Object[binsAndValues.size()];
Object[] values = new Object[binsAndValues.size()];
int i = 0;
for (Map.Entry<String, DistributionValue> entry : binsAndValues.entrySet()) {
bins[i] = entry.getKey();
values[i] = entry.getValue().absolute();
i++;
}
return new Object[][]{values, bins};
}
protected boolean isDistributionHistogram(Map<String, DistributionValue> binsAndValues) {
for (String type : DEEQU_TO_DBND.keySet()) {
if (!binsAndValues.containsKey(type)) {
return false;
}
}
return true;
}
protected String guessColumnTypeByDistribution(Map<String, DistributionValue> binsAndValues) {
for (Map.Entry<String, String> entry : DEEQU_TO_DBND.entrySet()) {
if (binsAndValues.get(entry.getKey()).absolute() > 1) {
return entry.getValue();
}
}
return "string";
}
protected boolean allBooleans(Object[] values) {
for (Object o : values) {
if (o != null && !"true".equalsIgnoreCase(o.toString()) && !"false".equalsIgnoreCase(o.toString())) {
return false;
}
}
return true;
}
protected boolean allIntegers(Object[] values) {
for (Object o : values) {
if (o != null && o.toString().contains(".")) {
return false;
}
if (o != null) {
try {
Integer.parseInt(o.toString());
} catch (NumberFormatException e) {
return false;
}
}
}
return true;
}
protected boolean allDoubles(Object[] values) {
for (Object o : values) {
if (o != null) {
try {
Double.parseDouble(o.toString());
} catch (NumberFormatException e) {
return false;
}
}
}
return true;
}
}
|
0
|
java-sources/ai/databand/dbnd-deequ/0.40.2/ai/databand
|
java-sources/ai/databand/dbnd-deequ/0.40.2/ai/databand/deequ/NoopMetricsRepository.java
|
package ai.databand.deequ;
import com.amazon.deequ.analyzers.runners.AnalyzerContext;
import com.amazon.deequ.repository.MetricsRepository;
import com.amazon.deequ.repository.MetricsRepositoryMultipleResultsLoader;
import com.amazon.deequ.repository.ResultKey;
import scala.Option;
/**
* Default noop deequ metrics repository.
*/
public class NoopMetricsRepository implements MetricsRepository {
@Override
public void save(ResultKey resultKey, AnalyzerContext analyzerContext) {
}
@Override
public Option<AnalyzerContext> loadByKey(ResultKey resultKey) {
return Option.empty();
}
@Override
public MetricsRepositoryMultipleResultsLoader load() {
return null;
}
}
|
0
|
java-sources/ai/databand/dbnd-mlflow/1.0.28.1/ai/databand
|
java-sources/ai/databand/dbnd-mlflow/1.0.28.1/ai/databand/mlflow/DbndMlflowClient.java
|
/*
* © Copyright Databand.ai, an IBM Company 2022
*/
package ai.databand.mlflow;
import ai.databand.DbndApi;
import ai.databand.DbndApiBuilder;
import ai.databand.RandomNames;
import ai.databand.config.DbndConfig;
import ai.databand.id.Sha1Long;
import ai.databand.id.Sha1Short;
import ai.databand.id.Uuid5;
import ai.databand.schema.InitRun;
import ai.databand.schema.InitRunArgs;
import ai.databand.schema.LogMetric;
import ai.databand.schema.Metric;
import ai.databand.schema.NewRunInfo;
import ai.databand.schema.RootRun;
import ai.databand.schema.SetRunState;
import ai.databand.schema.TaskDefinition;
import ai.databand.schema.TaskParamDefinition;
import ai.databand.schema.TaskRun;
import ai.databand.schema.TaskRunAttemptUpdate;
import ai.databand.schema.TaskRunEnv;
import ai.databand.schema.TaskRunParam;
import ai.databand.schema.TaskRunsInfo;
import ai.databand.schema.UpdateTaskRunAttempts;
import org.mlflow.api.proto.Service;
import org.mlflow.tracking.MlflowClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Response;
import java.io.IOException;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Collections;
public class DbndMlflowClient extends MlflowClient {
private static final Logger LOG = LoggerFactory.getLogger(DbndMlflowClient.class);
private final DbndApi dbnd;
private final MlflowClient mlflowClient;
private final String dbndTrackingUri;
public static MlflowClient newClient() {
DbndConfig config = new DbndConfig();
String trackerUrl = config.databandUrl();
MlflowClient mlflowClient = System.getenv("MLFLOW_TRACKING_URI") == null ? new StubMlFlowClient() : new MlflowClient();
return new DbndMlflowClient(mlflowClient, trackerUrl);
}
public DbndMlflowClient(MlflowClient mlflowClient, String dbndTrackingUri) {
this(mlflowClient, dbndTrackingUri, new DbndConfig());
}
public DbndMlflowClient(MlflowClient mlflowClient, String dbndTrackingUri, DbndConfig config) {
super("http://127.0.0.1");
this.dbndTrackingUri = dbndTrackingUri;
this.mlflowClient = mlflowClient;
dbnd = new DbndApiBuilder(config).build();
}
public DbndApi dbndApi() {
return dbnd;
}
@Override
public Service.RunInfo createRun(Service.CreateRun request) {
Service.RunInfo mlFlowRunInfo = mlflowClient.createRun(request);
String experimentId = request.getExperimentId();
String userId = request.getUserId();
String runUid = uuid5("RUN_UID", experimentId);
String rootRunUid = runUid;
String driverTaskUid = uuid5("DRIVER_TASK", experimentId);
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
String jobName = "embed_mlflow";
String rootRunUrl = String.format("%s/app/jobs/%s/%s", dbndTrackingUri, jobName, runUid);
String taskRunEnvUid = uuid5("TASK_RUN_ENV_UID", experimentId);
String taskRunUid = driverTaskUid;
String userCodeVersion = uuid5("USER_CODE_VERSION", experimentId);
String taskRunAttemptUid = uuid5("TASK_RUN_ATTEMPT", experimentId);
String machine = "mlflow machine";
String cmd = "mlflow run";
String databandVersion = "0.24.0";
String version = "mlflowVersion";
String taskSignature = sha1short("TASK_SIGNATURE", experimentId);
String taskDefinitionUid = uuid5("TASK_DEFINITION", experimentId);
String taskAfId = "mlflow_driver__" + sha1short("TASK_AF", experimentId);
String env = "mlflow";
InitRun data = new InitRun(
new InitRunArgs(
runUid,
rootRunUid,
driverTaskUid,
new NewRunInfo(
null,
env,
null,
"mlflow_inproces",
now,
now,
false,
"mlflow",
false,
runUid,
"mlflow cloud",
"unknown",
runUid,
jobName,
userId,
null,
RandomNames.next(),
"RUNNING",
now,
new RootRun(
rootRunUrl,
null,
rootRunUid,
null
)
),
new TaskRunEnv(
"None",
taskRunEnvUid,
userId,
userCodeVersion,
machine,
cmd,
now,
databandVersion,
"/",
true
),
new TaskRunsInfo(
taskRunEnvUid,
Collections.emptyList(),
runUid,
Collections.singletonList(
new TaskRun(
runUid,
true,
false,
null,
version,
taskRunUid,
taskSignature,
jobName,
Collections.singletonList(
new TaskRunParam(
"True",
"context",
"_meta_input"
)
),
taskSignature,
false,
now.toLocalDate(),
now,
"/logs",
"RUNNING",
taskDefinitionUid,
cmd,
false,
false,
taskRunAttemptUid,
taskAfId,
false,
false,
cmd,
taskAfId,
"mlflow",
Collections.emptyMap()
)
),
Collections.emptyList(),
rootRunUid,
Collections.emptyList(),
false,
Collections.singletonList(
new TaskDefinition(
"mlflow_task",
"...",
sha1long("SOURCE", experimentId),
"",
taskDefinitionUid,
sha1long("MODULE_SOURCE", experimentId),
Collections.singletonList(
new TaskParamDefinition(
"_meta_input",
"task_input",
"user",
false,
true,
"bool",
"",
"NOTHING"
)
),
"mlflow_task",
"java",
"..."
)
),
null
)
)
);
try {
Response<Void> res = dbnd.initRun(data).execute();
if (res.isSuccessful()) {
LOG.info("[task_run: {}] Run created", experimentId);
} else {
LOG.error("[task_run: {}] Unable to create run", experimentId);
}
} catch (IOException e) {
LOG.error(String.format("[task_run: %s] Unable to create run", data.getInitArgs()), e);
}
return mlFlowRunInfo;
}
/**
* We should complete task run attempt as well as task run here.
*
* @param runId MlFlow run id
*/
@Override
public void setTerminated(String runId) {
mlflowClient.setTerminated(runId);
String runUid = uuid5("RUN_UID", runId);
String taskRunAttemptUid = uuid5("TASK_RUN_ATTEMPT", runId);
String taskRunUid = uuid5("DRIVER_TASK", runId);
UpdateTaskRunAttempts taskRunAttempts = new UpdateTaskRunAttempts(
Collections.singletonList(
new TaskRunAttemptUpdate(
taskRunUid,
taskRunAttemptUid,
"SUCCESS",
ZonedDateTime.now(ZoneOffset.UTC),
ZonedDateTime.now(ZoneOffset.UTC),
null
)
)
);
try {
Response<Void> res = dbnd.updateTaskRunAttempts(taskRunAttempts).execute();
if (res.isSuccessful()) {
LOG.info("[task_run: {}] Completed", runUid);
} else {
LOG.error("[task_run: {}] Unable to complete task run attempt", runUid);
}
} catch (IOException e) {
LOG.error(String.format("[task_run: %s] Unable to complete task run attempt", runUid), e);
}
SetRunState data = new SetRunState(
runUid,
"SUCCESS",
ZonedDateTime.now(ZoneOffset.UTC)
);
try {
Response<Void> res = dbnd.setRunState(data).execute();
if (res.isSuccessful()) {
LOG.info("[task_run: {}] Completed", runUid);
} else {
LOG.error("[task_run: {}] Unable to complete run", runUid);
}
} catch (IOException e) {
LOG.error(String.format("[task_run: %s] Unable to complete run", runUid), e);
}
}
@Override
public void logMetric(String runId, String key, double value, long timestamp, long step) {
String taskRunAttemptUid = uuid5("TASK_RUN_ATTEMPT", runId);
mlflowClient.logMetric(runId, key, value, timestamp, step);
LogMetric data = new LogMetric(
taskRunAttemptUid,
new Metric(
key,
String.valueOf(value),
ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC)
)
);
try {
Response<Void> res = dbnd.logMetric(data).execute();
if (res.isSuccessful()) {
LOG.info("[task_run: {}] Sent metric [{}]:[{}]", taskRunAttemptUid, key, value);
} else {
LOG.error("[task_run: {}] Unable to send metric", taskRunAttemptUid);
}
} catch (IOException e) {
LOG.error(String.format("[task_run: %s] Unable to send metric", taskRunAttemptUid), e);
}
}
protected String sha1short(String namespace, String name) {
return new Sha1Short(namespace, name).toString();
}
protected String sha1long(String namespace, String name) {
return new Sha1Long(namespace, name).toString();
}
protected String uuid5(String namespace, String name) {
return new Uuid5(namespace, name).toString();
}
private static class StubMlFlowClient extends MlflowClient {
public StubMlFlowClient() {
super("http://127.0.0.1");
}
@Override
public void logMetric(String runId, String key, double value, long timestamp, long step) {
// do nothing
}
@Override
public Service.RunInfo createRun(Service.CreateRun request) {
Service.RunInfo.Builder builder = Service.RunInfo.newBuilder();
builder.setExperimentId(request.getExperimentId());
builder.setStartTime(request.getStartTime());
builder.setUserId(request.getUserId());
return builder.build();
}
@Override
public void setTerminated(String runId) {
// do nothing
}
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/ad
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/ad/utils/UUIDUtils.java
|
package ai.datatower.ad.utils;
import java.util.Random;
public class UUIDUtils {
public static String generateUUID() {
StringBuilder uuid = new StringBuilder();
for (int i = 0; i < 16; i++) {
uuid.append(Integer.toHexString(new Random().nextInt(16)));
}
return uuid.toString();
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/BuildConfig.java
|
/**
* Automatically generated file. DO NOT MODIFY
*/
package ai.datatower.analytics;
public final class BuildConfig {
public static final boolean DEBUG = false;
public static final String LIBRARY_PACKAGE_NAME = "ai.datatower.analytics";
public static final String BUILD_TYPE = "release";
public static final String FLAVOR = "public";
// Field from default config.
public static final String DEFAULT_SERVER_URL = "";
// Field from default config.
public static final String ERROR_REPORTING_URL = "";
// Field from default config.
public static final String EVENT_REPORT_PATH = "";
// Field from product flavor: public
public static final Boolean IS_LOGGING_ENABLED = false;
// Field from build type: release
public static final String VERSION_NAME = "3.2.0";
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/core/DTActivityLifecycleCallbacks.java
|
/*
* Copyright (C) 2022 ThinkingData
*/
package ai.datatower.analytics.core;
import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import ai.datatower.analytics.Constant;
import ai.datatower.analytics.config.AnalyticsConfig;
import ai.datatower.analytics.utils.LogUtils;
import ai.datatower.analytics.utils.MemoryUtils;
public class DTActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
private static final String TAG = Constant.LOG_TAG;
private boolean resumeFromBackground = false;
private final Object mActivityLifecycleCallbacksLock = new Object();
private volatile Boolean isLaunch = true;
private WeakReference<Activity> mCurrentActivity;
private final List<WeakReference<Activity>> mStartedActivityList = new ArrayList<>();
//标识是否采集end事件
private boolean shouldTrackEndEvent = true;
public Activity currentActivity() {
if (mCurrentActivity != null) {
return mCurrentActivity.get();
}
return null;
}
public void trackSessionStart(){
if (AnalyticsConfig.Companion.getInstance().isSdkDisable()) {
return;
}
if (isLaunch || resumeFromBackground) {
isLaunch = false;
PropertyManager.Companion.getInstance().updateIsForeground(true, resumeFromBackground, getStartReason());
}
}
private void trackSessionEnd(){
if (AnalyticsConfig.Companion.getInstance().isSdkDisable()) {
return;
}
PropertyManager.Companion.getInstance().updateIsForeground(false, resumeFromBackground,"");
}
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
mCurrentActivity = new WeakReference<>(activity);
MemoryUtils.toggleShouldListenFps(true);
}
private boolean notStartedActivity(Activity activity, boolean remove) {
synchronized (mActivityLifecycleCallbacksLock) {
Iterator<WeakReference<Activity>> it = mStartedActivityList.iterator();
while (it.hasNext()) {
WeakReference<Activity> current = it.next();
if (current.get() == activity) {
if (remove) {
it.remove();
}
return false;
}
}
return true;
}
}
@Override
public void onActivityStarted(Activity activity) {
mCurrentActivity = new WeakReference<>(activity);
MemoryUtils.toggleShouldListenFps(true);
try {
synchronized (mActivityLifecycleCallbacksLock) {
if (mStartedActivityList.size() == 0) {
trackSessionStart();
}
if (notStartedActivity(activity, false)) {
mStartedActivityList.add(new WeakReference<>(activity));
} else {
LogUtils.w(TAG, "Unexpected state. The activity might not be stopped correctly: " + activity);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onActivityResumed(Activity activity) {
synchronized (mActivityLifecycleCallbacksLock) {
MemoryUtils.toggleShouldListenFps(true);
if (notStartedActivity(activity, false)) {
LogUtils.i(TAG, "onActivityResumed: the SDK was initialized after the onActivityStart of " + activity);
mStartedActivityList.add(new WeakReference<>(activity));
if (mStartedActivityList.size() == 1) {
trackSessionStart();
}
}
}
}
@Override
public void onActivityPaused(Activity activity) {
synchronized (mActivityLifecycleCallbacksLock) {
MemoryUtils.toggleShouldListenFps(false);
if (notStartedActivity(activity, false)) {
LogUtils.i(TAG, "onActivityPaused: the SDK was initialized after the onActivityStart of " + activity);
mStartedActivityList.add(new WeakReference<>(activity));
if (mStartedActivityList.size() == 1) {
trackSessionStart();
}
}
}
}
void onAppStartEventEnabled() {
synchronized (mActivityLifecycleCallbacksLock) {
if (isLaunch) {
TimerTask task = new TimerTask() {
@Override
public void run() {
if (isLaunch) {
isLaunch = false;
PropertyManager.Companion.getInstance().updateIsForeground(true, resumeFromBackground, getStartReason());
}
}
};
Timer timer = new Timer();
timer.schedule(task, 100); //100ms后执行TimeTask的run方法
}
}
}
public static Object wrap(Object o) {
if (o == null) {
return JSONObject.NULL;
}
if (o instanceof JSONArray || o instanceof JSONObject) {
return o;
}
if (o.equals(JSONObject.NULL)) {
return o;
}
try {
if (o instanceof Collection) {
return new JSONArray((Collection) o);
} else if (o.getClass().isArray()) {
return toJSONArray(o);
}
if (o instanceof Map) {
return new JSONObject((Map) o);
}
if (o instanceof Boolean
|| o instanceof Byte
|| o instanceof Character
|| o instanceof Double
|| o instanceof Float
|| o instanceof Integer
|| o instanceof Long
|| o instanceof Short
|| o instanceof String) {
return o;
}
if (o.getClass().getPackage().getName().startsWith("java.")) {
return o.toString();
}
} catch (Exception ignored) {
//ignored
}
return null;
}
public static JSONArray toJSONArray(Object array) throws JSONException {
JSONArray result = new JSONArray();
if (!array.getClass().isArray()) {
throw new JSONException("Not a primitive array: " + array.getClass());
}
final int length = Array.getLength(array);
for (int i = 0; i < length; ++i) {
result.put(wrap(Array.get(array, i)));
}
return result;
}
String getStartReason() {
JSONObject object = new JSONObject();
JSONObject data = new JSONObject();
if (mCurrentActivity != null) {
try {
Activity activity = mCurrentActivity.get();
Intent intent = activity.getIntent();
if (intent != null) {
String uri = intent.getDataString();
if (!TextUtils.isEmpty(uri)) {
object.put("url", uri);
}
Bundle bundle = intent.getExtras();
if (bundle != null) {
Set<String> keys = bundle.keySet();
for (String key : keys) {
Object value = bundle.get(key);
Object supportValue = wrap(value);
if (supportValue != null && supportValue != JSONObject.NULL) {
data.put(key, wrap(value));
}
}
object.put("data", data);
}
}
} catch (Exception exception) {
//exception.printStackTrace();
return object.toString();
}
}
return object.toString();
}
@Override
public void onActivityStopped(Activity activity) {
try {
synchronized (mActivityLifecycleCallbacksLock) {
if (notStartedActivity(activity, true)) {
LogUtils.i(TAG, "onActivityStopped: the SDK might be initialized after the onActivityStart of " + activity);
return;
}
if (mStartedActivityList.size() == 0) {
mCurrentActivity = null;
if (shouldTrackEndEvent) {
try {
trackSessionEnd();
resumeFromBackground = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data/persistence/SharedPreferencesLoader.java
|
/*
* Copyright (C) 2022 ThinkingData
*/
package ai.datatower.analytics.data.persistence;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class SharedPreferencesLoader {
private final Executor mExecutor;
public SharedPreferencesLoader() {
mExecutor = Executors.newSingleThreadExecutor();
}
public Future<SharedPreferences> loadPreferences(Context context, String name) {
final LoadSharedPreferences loadSharedPrefs =
new LoadSharedPreferences(context, name);
final FutureTask<SharedPreferences> future
= new FutureTask<>(loadSharedPrefs);
mExecutor.execute(future);
return future;
}
private static class LoadSharedPreferences implements Callable<SharedPreferences> {
private final Context mContext;
private final String mPrefsName;
public LoadSharedPreferences(Context context, String prefsName) {
mContext = context;
mPrefsName = prefsName;
}
@Override
public SharedPreferences call() {
return mContext.getSharedPreferences(mPrefsName, Context.MODE_PRIVATE);
}
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data/persistence/SharedPreferencesStorage.java
|
/*
* Copyright (C) 2022 ThinkingData
*/
package ai.datatower.analytics.data.persistence;
import android.content.SharedPreferences;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
abstract class SharedPreferencesStorage<T> {
protected T data;
final String storageKey;
private final Future<SharedPreferences> loadStoredPreferences;
SharedPreferencesStorage(final Future<SharedPreferences> loadStoredPreferences, final String storageKey) {
this.loadStoredPreferences = loadStoredPreferences;
this.storageKey = storageKey;
}
// return default value.
T create() {
return null;
}
// save the data to sharedPreference. If the type of T is not String, override this method.
void save(SharedPreferences.Editor editor, T data) {
editor.putString(storageKey, (String) data);
editor.apply();
}
// load the data from sharedPreference. If the type of T is not String, override this method.
void load(SharedPreferences sharedPreferences) {
String data = sharedPreferences.getString(this.storageKey, null);
if (data == null) {
put(create());
} else {
this.data = (T) data;
}
}
/**
* 获取保存在 SharedPreference 中的值.
*
* @return value of the storageKey.
*/
public T get() {
if (this.data == null) {
synchronized (loadStoredPreferences) {
SharedPreferences sharedPreferences = null;
try {
sharedPreferences = loadStoredPreferences.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (sharedPreferences != null) {
load(sharedPreferences);
}
}
}
return this.data;
}
/**
* 设置 storage key 的值,并保存到 sharedPreference 中.
*
* @param data 需要设置的值.
*/
public void put(T data) {
this.data = data;
synchronized (loadStoredPreferences) {
final SharedPreferences.Editor editor = getEditor();
if (editor != null) {
save(editor, this.data);
}
}
}
private SharedPreferences.Editor getEditor() {
SharedPreferences sharedPreferences = null;
try {
sharedPreferences = loadStoredPreferences.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (sharedPreferences != null) {
return sharedPreferences.edit();
} else {
return null;
}
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data/persistence/StorageDisableFlag.java
|
/*
* Copyright (C) 2022 ThinkingData
*/
package ai.datatower.analytics.data.persistence;
import android.content.SharedPreferences;
import java.util.concurrent.Future;
/**
* StorageDisableFlag.
* */
public class StorageDisableFlag extends SharedPreferencesStorage<Boolean> {
public StorageDisableFlag(Future<SharedPreferences> loadStoredPreferences) {
super(loadStoredPreferences, "disableFlag");
}
@Override
protected void save(SharedPreferences.Editor editor, Boolean data) {
editor.putBoolean(storageKey, data);
editor.apply();
}
@Override
protected void load(SharedPreferences sharedPreferences) {
data = sharedPreferences.getBoolean(this.storageKey, false);
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data/persistence/StorageReportUrl.java
|
/*
* Copyright (C) 2022 ThinkingData
*/
package ai.datatower.analytics.data.persistence;
import android.content.SharedPreferences;
import java.util.concurrent.Future;
/**
* StorageReportUrl.
*/
public class StorageReportUrl extends SharedPreferencesStorage<String> {
public StorageReportUrl(Future<SharedPreferences> loadStoredPreferences) {
super(loadStoredPreferences, "reportUrl");
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data/room/DTAnalyticsDB_Impl.java
|
package ai.datatower.analytics.data.room;
import ai.datatower.analytics.data.room.dao.ConfigsDao;
import ai.datatower.analytics.data.room.dao.ConfigsDao_Impl;
import ai.datatower.analytics.data.room.dao.EventInfoDao;
import ai.datatower.analytics.data.room.dao.EventInfoDao_Impl;
import androidx.annotation.NonNull;
import androidx.room.DatabaseConfiguration;
import androidx.room.InvalidationTracker;
import androidx.room.RoomOpenHelper;
import androidx.room.RoomOpenHelper.Delegate;
import androidx.room.RoomOpenHelper.ValidationResult;
import androidx.room.migration.AutoMigrationSpec;
import androidx.room.migration.Migration;
import androidx.room.util.DBUtil;
import androidx.room.util.TableInfo;
import androidx.room.util.TableInfo.Column;
import androidx.room.util.TableInfo.ForeignKey;
import androidx.room.util.TableInfo.Index;
import androidx.sqlite.db.SupportSQLiteDatabase;
import androidx.sqlite.db.SupportSQLiteOpenHelper;
import androidx.sqlite.db.SupportSQLiteOpenHelper.Callback;
import androidx.sqlite.db.SupportSQLiteOpenHelper.Configuration;
import java.lang.Class;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.Generated;
@Generated("androidx.room.RoomProcessor")
@SuppressWarnings({"unchecked", "deprecation"})
public final class DTAnalyticsDB_Impl extends DTAnalyticsDB {
private volatile EventInfoDao _eventInfoDao;
private volatile ConfigsDao _configsDao;
@Override
protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration configuration) {
final SupportSQLiteOpenHelper.Callback _openCallback = new RoomOpenHelper(configuration, new RoomOpenHelper.Delegate(2) {
@Override
public void createAllTables(SupportSQLiteDatabase _db) {
_db.execSQL("CREATE TABLE IF NOT EXISTS `events` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `event_syn` TEXT, `data` TEXT NOT NULL, `created_at` INTEGER NOT NULL)");
_db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS `index_events_event_syn` ON `events` (`event_syn`)");
_db.execSQL("CREATE TABLE IF NOT EXISTS `configs` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `value` TEXT)");
_db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)");
_db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '9c4b662c22d516204858892322f9aad0')");
}
@Override
public void dropAllTables(SupportSQLiteDatabase _db) {
_db.execSQL("DROP TABLE IF EXISTS `events`");
_db.execSQL("DROP TABLE IF EXISTS `configs`");
if (mCallbacks != null) {
for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
mCallbacks.get(_i).onDestructiveMigration(_db);
}
}
}
@Override
protected void onCreate(SupportSQLiteDatabase _db) {
if (mCallbacks != null) {
for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
mCallbacks.get(_i).onCreate(_db);
}
}
}
@Override
public void onOpen(SupportSQLiteDatabase _db) {
mDatabase = _db;
internalInitInvalidationTracker(_db);
if (mCallbacks != null) {
for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
mCallbacks.get(_i).onOpen(_db);
}
}
}
@Override
public void onPreMigrate(SupportSQLiteDatabase _db) {
DBUtil.dropFtsSyncTriggers(_db);
}
@Override
public void onPostMigrate(SupportSQLiteDatabase _db) {
}
@Override
protected RoomOpenHelper.ValidationResult onValidateSchema(SupportSQLiteDatabase _db) {
final HashMap<String, TableInfo.Column> _columnsEvents = new HashMap<String, TableInfo.Column>(4);
_columnsEvents.put("_id", new TableInfo.Column("_id", "INTEGER", true, 1, null, TableInfo.CREATED_FROM_ENTITY));
_columnsEvents.put("event_syn", new TableInfo.Column("event_syn", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsEvents.put("data", new TableInfo.Column("data", "TEXT", true, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsEvents.put("created_at", new TableInfo.Column("created_at", "INTEGER", true, 0, null, TableInfo.CREATED_FROM_ENTITY));
final HashSet<TableInfo.ForeignKey> _foreignKeysEvents = new HashSet<TableInfo.ForeignKey>(0);
final HashSet<TableInfo.Index> _indicesEvents = new HashSet<TableInfo.Index>(1);
_indicesEvents.add(new TableInfo.Index("index_events_event_syn", true, Arrays.asList("event_syn"), Arrays.asList("ASC")));
final TableInfo _infoEvents = new TableInfo("events", _columnsEvents, _foreignKeysEvents, _indicesEvents);
final TableInfo _existingEvents = TableInfo.read(_db, "events");
if (! _infoEvents.equals(_existingEvents)) {
return new RoomOpenHelper.ValidationResult(false, "events(ai.datatower.analytics.data.room.bean.Events).\n"
+ " Expected:\n" + _infoEvents + "\n"
+ " Found:\n" + _existingEvents);
}
final HashMap<String, TableInfo.Column> _columnsConfigs = new HashMap<String, TableInfo.Column>(3);
_columnsConfigs.put("_id", new TableInfo.Column("_id", "INTEGER", true, 1, null, TableInfo.CREATED_FROM_ENTITY));
_columnsConfigs.put("name", new TableInfo.Column("name", "TEXT", true, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsConfigs.put("value", new TableInfo.Column("value", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
final HashSet<TableInfo.ForeignKey> _foreignKeysConfigs = new HashSet<TableInfo.ForeignKey>(0);
final HashSet<TableInfo.Index> _indicesConfigs = new HashSet<TableInfo.Index>(0);
final TableInfo _infoConfigs = new TableInfo("configs", _columnsConfigs, _foreignKeysConfigs, _indicesConfigs);
final TableInfo _existingConfigs = TableInfo.read(_db, "configs");
if (! _infoConfigs.equals(_existingConfigs)) {
return new RoomOpenHelper.ValidationResult(false, "configs(ai.datatower.analytics.data.room.bean.Configs).\n"
+ " Expected:\n" + _infoConfigs + "\n"
+ " Found:\n" + _existingConfigs);
}
return new RoomOpenHelper.ValidationResult(true, null);
}
}, "9c4b662c22d516204858892322f9aad0", "ee908d61a3c3f9c328ad3b8900b00d42");
final SupportSQLiteOpenHelper.Configuration _sqliteConfig = SupportSQLiteOpenHelper.Configuration.builder(configuration.context)
.name(configuration.name)
.callback(_openCallback)
.build();
final SupportSQLiteOpenHelper _helper = configuration.sqliteOpenHelperFactory.create(_sqliteConfig);
return _helper;
}
@Override
protected InvalidationTracker createInvalidationTracker() {
final HashMap<String, String> _shadowTablesMap = new HashMap<String, String>(0);
HashMap<String, Set<String>> _viewTables = new HashMap<String, Set<String>>(0);
return new InvalidationTracker(this, _shadowTablesMap, _viewTables, "events","configs");
}
@Override
public void clearAllTables() {
super.assertNotMainThread();
final SupportSQLiteDatabase _db = super.getOpenHelper().getWritableDatabase();
try {
super.beginTransaction();
_db.execSQL("DELETE FROM `events`");
_db.execSQL("DELETE FROM `configs`");
super.setTransactionSuccessful();
} finally {
super.endTransaction();
_db.query("PRAGMA wal_checkpoint(FULL)").close();
if (!_db.inTransaction()) {
_db.execSQL("VACUUM");
}
}
}
@Override
protected Map<Class<?>, List<Class<?>>> getRequiredTypeConverters() {
final HashMap<Class<?>, List<Class<?>>> _typeConvertersMap = new HashMap<Class<?>, List<Class<?>>>();
_typeConvertersMap.put(EventInfoDao.class, EventInfoDao_Impl.getRequiredConverters());
_typeConvertersMap.put(ConfigsDao.class, ConfigsDao_Impl.getRequiredConverters());
return _typeConvertersMap;
}
@Override
public Set<Class<? extends AutoMigrationSpec>> getRequiredAutoMigrationSpecs() {
final HashSet<Class<? extends AutoMigrationSpec>> _autoMigrationSpecsSet = new HashSet<Class<? extends AutoMigrationSpec>>();
return _autoMigrationSpecsSet;
}
@Override
public List<Migration> getAutoMigrations(
@NonNull Map<Class<? extends AutoMigrationSpec>, AutoMigrationSpec> autoMigrationSpecsMap) {
return Arrays.asList();
}
@Override
public EventInfoDao getEventsDao() {
if (_eventInfoDao != null) {
return _eventInfoDao;
} else {
synchronized(this) {
if(_eventInfoDao == null) {
_eventInfoDao = new EventInfoDao_Impl(this);
}
return _eventInfoDao;
}
}
}
@Override
public ConfigsDao getConfigDao() {
if (_configsDao != null) {
return _configsDao;
} else {
synchronized(this) {
if(_configsDao == null) {
_configsDao = new ConfigsDao_Impl(this);
}
return _configsDao;
}
}
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data/room
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data/room/dao/ConfigsDao_Impl.java
|
package ai.datatower.analytics.data.room.dao;
import ai.datatower.analytics.data.room.bean.Configs;
import android.database.Cursor;
import androidx.room.EntityInsertionAdapter;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.room.SharedSQLiteStatement;
import androidx.room.util.DBUtil;
import androidx.sqlite.db.SupportSQLiteStatement;
import java.lang.Class;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.Collections;
import java.util.List;
import javax.annotation.processing.Generated;
@Generated("androidx.room.RoomProcessor")
@SuppressWarnings({"unchecked", "deprecation"})
public final class ConfigsDao_Impl implements ConfigsDao {
private final RoomDatabase __db;
private final EntityInsertionAdapter<Configs> __insertionAdapterOfConfigs;
private final SharedSQLiteStatement __preparedStmtOfUpdate;
public ConfigsDao_Impl(RoomDatabase __db) {
this.__db = __db;
this.__insertionAdapterOfConfigs = new EntityInsertionAdapter<Configs>(__db) {
@Override
public String createQuery() {
return "INSERT OR ABORT INTO `configs` (`_id`,`name`,`value`) VALUES (nullif(?, 0),?,?)";
}
@Override
public void bind(SupportSQLiteStatement stmt, Configs value) {
stmt.bindLong(1, value.getId());
if (value.getName() == null) {
stmt.bindNull(2);
} else {
stmt.bindString(2, value.getName());
}
if (value.getValue() == null) {
stmt.bindNull(3);
} else {
stmt.bindString(3, value.getValue());
}
}
};
this.__preparedStmtOfUpdate = new SharedSQLiteStatement(__db) {
@Override
public String createQuery() {
final String _query = "update configs set value = ? where name = ?";
return _query;
}
};
}
@Override
public void insert(final Configs... config) {
__db.assertNotSuspendingTransaction();
__db.beginTransaction();
try {
__insertionAdapterOfConfigs.insert(config);
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
@Override
public void update(final String name, final String value) {
__db.assertNotSuspendingTransaction();
final SupportSQLiteStatement _stmt = __preparedStmtOfUpdate.acquire();
int _argIndex = 1;
if (value == null) {
_stmt.bindNull(_argIndex);
} else {
_stmt.bindString(_argIndex, value);
}
_argIndex = 2;
if (name == null) {
_stmt.bindNull(_argIndex);
} else {
_stmt.bindString(_argIndex, name);
}
__db.beginTransaction();
try {
_stmt.executeUpdateDelete();
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
__preparedStmtOfUpdate.release(_stmt);
}
}
@Override
public String queryValueByName(final String name) {
final String _sql = "select value from configs where name =?";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
int _argIndex = 1;
if (name == null) {
_statement.bindNull(_argIndex);
} else {
_statement.bindString(_argIndex, name);
}
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final String _result;
if(_cursor.moveToFirst()) {
if (_cursor.isNull(0)) {
_result = null;
} else {
_result = _cursor.getString(0);
}
} else {
_result = null;
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
@Override
public int existsValue(final String name) {
final String _sql = "select count(*) from configs where name = ?";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
int _argIndex = 1;
if (name == null) {
_statement.bindNull(_argIndex);
} else {
_statement.bindString(_argIndex, name);
}
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _result;
if(_cursor.moveToFirst()) {
_result = _cursor.getInt(0);
} else {
_result = 0;
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
public static List<Class<?>> getRequiredConverters() {
return Collections.emptyList();
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data/room
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/data/room/dao/EventInfoDao_Impl.java
|
package ai.datatower.analytics.data.room.dao;
import ai.datatower.analytics.data.room.bean.Events;
import android.database.Cursor;
import androidx.room.EntityDeletionOrUpdateAdapter;
import androidx.room.EntityInsertionAdapter;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.room.SharedSQLiteStatement;
import androidx.room.util.DBUtil;
import androidx.room.util.StringUtil;
import androidx.sqlite.db.SupportSQLiteStatement;
import java.lang.Class;
import java.lang.Override;
import java.lang.String;
import java.lang.StringBuilder;
import java.lang.SuppressWarnings;
import java.util.Collections;
import java.util.List;
import javax.annotation.processing.Generated;
@Generated("androidx.room.RoomProcessor")
@SuppressWarnings({"unchecked", "deprecation"})
public final class EventInfoDao_Impl implements EventInfoDao {
private final RoomDatabase __db;
private final EntityInsertionAdapter<Events> __insertionAdapterOfEvents;
private final EntityDeletionOrUpdateAdapter<Events> __deletionAdapterOfEvents;
private final SharedSQLiteStatement __preparedStmtOfDeleteTheOldestData;
private final SharedSQLiteStatement __preparedStmtOfDeleteEventByEventSyn;
private final SharedSQLiteStatement __preparedStmtOfClearTable;
public EventInfoDao_Impl(RoomDatabase __db) {
this.__db = __db;
this.__insertionAdapterOfEvents = new EntityInsertionAdapter<Events>(__db) {
@Override
public String createQuery() {
return "INSERT OR ABORT INTO `events` (`_id`,`event_syn`,`data`,`created_at`) VALUES (nullif(?, 0),?,?,?)";
}
@Override
public void bind(SupportSQLiteStatement stmt, Events value) {
stmt.bindLong(1, value.getId());
if (value.getEventSyn() == null) {
stmt.bindNull(2);
} else {
stmt.bindString(2, value.getEventSyn());
}
if (value.getData() == null) {
stmt.bindNull(3);
} else {
stmt.bindString(3, value.getData());
}
stmt.bindLong(4, value.getCreatedAt());
}
};
this.__deletionAdapterOfEvents = new EntityDeletionOrUpdateAdapter<Events>(__db) {
@Override
public String createQuery() {
return "DELETE FROM `events` WHERE `_id` = ?";
}
@Override
public void bind(SupportSQLiteStatement stmt, Events value) {
stmt.bindLong(1, value.getId());
}
};
this.__preparedStmtOfDeleteTheOldestData = new SharedSQLiteStatement(__db) {
@Override
public String createQuery() {
final String _query = "DELETE FROM events WHERE _id IN ( SELECT t._id FROM ( SELECT _id FROM events ORDER BY _id ASC LIMIT ? ) AS t)";
return _query;
}
};
this.__preparedStmtOfDeleteEventByEventSyn = new SharedSQLiteStatement(__db) {
@Override
public String createQuery() {
final String _query = "DELETE FROM events WHERE event_syn=?";
return _query;
}
};
this.__preparedStmtOfClearTable = new SharedSQLiteStatement(__db) {
@Override
public String createQuery() {
final String _query = "delete from events";
return _query;
}
};
}
@Override
public long insertEvent(final Events events) {
__db.assertNotSuspendingTransaction();
__db.beginTransaction();
try {
long _result = __insertionAdapterOfEvents.insertAndReturnId(events);
__db.setTransactionSuccessful();
return _result;
} finally {
__db.endTransaction();
}
}
@Override
public void delete(final Events event) {
__db.assertNotSuspendingTransaction();
__db.beginTransaction();
try {
__deletionAdapterOfEvents.handle(event);
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
@Override
public void deleteTheOldestData(final int num) {
__db.assertNotSuspendingTransaction();
final SupportSQLiteStatement _stmt = __preparedStmtOfDeleteTheOldestData.acquire();
int _argIndex = 1;
_stmt.bindLong(_argIndex, num);
__db.beginTransaction();
try {
_stmt.executeUpdateDelete();
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
__preparedStmtOfDeleteTheOldestData.release(_stmt);
}
}
@Override
public void deleteEventByEventSyn(final String eventSyn) {
__db.assertNotSuspendingTransaction();
final SupportSQLiteStatement _stmt = __preparedStmtOfDeleteEventByEventSyn.acquire();
int _argIndex = 1;
if (eventSyn == null) {
_stmt.bindNull(_argIndex);
} else {
_stmt.bindString(_argIndex, eventSyn);
}
__db.beginTransaction();
try {
_stmt.executeUpdateDelete();
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
__preparedStmtOfDeleteEventByEventSyn.release(_stmt);
}
}
@Override
public void clearTable() {
__db.assertNotSuspendingTransaction();
final SupportSQLiteStatement _stmt = __preparedStmtOfClearTable.acquire();
__db.beginTransaction();
try {
_stmt.executeUpdateDelete();
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
__preparedStmtOfClearTable.release(_stmt);
}
}
@Override
public String[] queryEventData(final int limit) {
final String _sql = "SELECT data FROM events limit 0,? ";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
int _argIndex = 1;
_statement.bindLong(_argIndex, limit);
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final String[] _result = new String[_cursor.getCount()];
int _index = 0;
while(_cursor.moveToNext()) {
final String _item;
if (_cursor.isNull(0)) {
_item = null;
} else {
_item = _cursor.getString(0);
}
_result[_index] = _item;
_index ++;
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
@Override
public int dataCount() {
final String _sql = "select count(*) as num from events";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _result;
if(_cursor.moveToFirst()) {
_result = _cursor.getInt(0);
} else {
_result = 0;
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
@Override
public void deleteBatchEventByEventSyn(final List<String> eventSyn) {
__db.assertNotSuspendingTransaction();
StringBuilder _stringBuilder = StringUtil.newStringBuilder();
_stringBuilder.append("DELETE FROM events WHERE event_syn IN (");
final int _inputSize = eventSyn.size();
StringUtil.appendPlaceholders(_stringBuilder, _inputSize);
_stringBuilder.append(" )");
final String _sql = _stringBuilder.toString();
final SupportSQLiteStatement _stmt = __db.compileStatement(_sql);
int _argIndex = 1;
for (String _item : eventSyn) {
if (_item == null) {
_stmt.bindNull(_argIndex);
} else {
_stmt.bindString(_argIndex, _item);
}
_argIndex ++;
}
__db.beginTransaction();
try {
_stmt.executeUpdateDelete();
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
public static List<Class<?>> getRequiredConverters() {
return Collections.emptyList();
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/exception/InvalidDataException.java
|
/*
* Created by wangzhuozhou on 2015/08/01.
* Copyright 2015-2020 Sensors Data 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 ai.datatower.analytics.exception;
/**
* EventName, Properties Key/Value 格式错误
*/
public class InvalidDataException extends Exception {
public InvalidDataException(String error) {
super(error);
}
public InvalidDataException(Throwable throwable) {
super(throwable);
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/network/HttpMethod.java
|
/*
* Created by chenru on 2020/06/22.
* Copyright 2015-2020 Sensors Data 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 ai.datatower.analytics.network;
public enum HttpMethod {
POST_ASYNC,
GET_ASYNC,
POST_SYNC,
GET_SYNC
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/network/HttpService.java
|
/*
* Copyright (C) 2022 ThinkingData
*/
package ai.datatower.analytics.network;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidParameterException;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import ai.datatower.analytics.utils.LogUtils;
/**
* HttpService发送数据.
*/
public class HttpService implements RemoteService {
@Override
public String performRequest(String endpointUrl, String params,
boolean debug, SSLSocketFactory socketFactory,
Map<String, String> extraHeaders)
throws DTHttpException, IOException {
InputStream in = null;
OutputStream out = null;
BufferedOutputStream bout = null;
BufferedReader br = null;
HttpURLConnection connection = null;
try {
final URL url = new URL(endpointUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(15 * 1000);
connection.setReadTimeout(15 * 1000);
if (null != socketFactory && connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setSSLSocketFactory(socketFactory);
}
if (null != params) {
String query;
connection.setDoOutput(true);
connection.setRequestMethod("POST");
if (debug) {
query = params;
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setUseCaches(false);
connection.setRequestProperty("charset", "utf-8");
} else {
connection.setRequestProperty("Content-Type", "text/plain");
try {
query = encodeData(params);
} catch (IOException e) {
throw new InvalidParameterException(e.getMessage());
}
}
if (extraHeaders != null) {
for (Map.Entry<String, String> entry : extraHeaders.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.setFixedLengthStreamingMode(query.getBytes(StandardCharsets.UTF_8).length);
out = connection.getOutputStream();
bout = new BufferedOutputStream(out);
bout.write(query.getBytes(StandardCharsets.UTF_8));
bout.flush();
bout.close();
bout = null;
out.close();
out = null;
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
in = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
StringBuilder buffer = new StringBuilder();
String str;
while ((str = br.readLine()) != null) {
buffer.append(str);
}
in.close();
br.close();
return buffer.toString();
} else {
try {
in = connection.getErrorStream();
br = new BufferedReader(new InputStreamReader(in));
StringBuilder buffer = new StringBuilder();
String str;
while ((str = br.readLine()) != null) {
buffer.append(str);
}
in.close();
br.close();
throw new RemoteVerificationException(responseCode, buffer.toString());
} catch (Throwable t) {
if (t instanceof RemoteVerificationException) throw t;
LogUtils.e("DT Http", "Failed to get input stream: " + t.getMessage());
throw new ServiceUnavailableException(
"Service unavailable with response code: " + responseCode);
}
}
} else {
throw new InvalidParameterException("Content is null");
}
} finally {
if (null != bout) {
try {
bout.close();
} catch (final IOException e) {
//ignored
}
}
if (null != out) {
try {
out.close();
} catch (final IOException e) {
//ignored
}
}
if (null != in) {
try {
in.close();
} catch (final IOException ignored) {
//ignored
}
}
if (null != br) {
try {
br.close();
} catch (final IOException ignored) {
//ignored
}
}
if (null != connection) {
connection.disconnect();
}
}
}
private String encodeData(final String rawMessage) throws IOException {
// ByteArrayOutputStream os = new ByteArrayOutputStream(rawMessage.getBytes().length);
// GZIPOutputStream gos = new GZIPOutputStream(os);
// gos.write(rawMessage.getBytes());
// gos.close();
// byte[] compressed = os.toByteArray();
// os.close();
return rawMessage;
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/network/HttpTaskManager.java
|
/*
* Created by chenru on 2020/06/22.
* Copyright 2015-2020 Sensors Data 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 ai.datatower.analytics.network;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import ai.datatower.analytics.utils.LogUtils;
class HttpTaskManager {
/**
* 创建一个可重用固定线程数的线程池
*/
private static final int POOL_SIZE = 1;
/**
* 创建一个可重用固定线程数的线程池
*/
private volatile static ExecutorService executor = null;
private HttpTaskManager() {
}
private static ExecutorService getInstance() {
if (executor == null) {
synchronized (HttpTaskManager.class) {
if (executor == null) {
executor = new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(), new ThreadFactoryWithName("HttpTaskManager"));
}
}
}
return executor;
}
/**
* 异步任务处理
*
* @param runnable 任务
*/
static void execute(Runnable runnable) {
getInstance().execute(runnable);
}
static class ThreadFactoryWithName implements ThreadFactory {
private final String name;
ThreadFactoryWithName(String name) {
this.name = name;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, name);
thread.setUncaughtExceptionHandler((t, e) -> LogUtils.e(e.getMessage()));
return thread;
}
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/network/HttpUtils.java
|
/*
* Created by chenru on 2020/06/22.
* Copyright 2015-2020 Sensors Data 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 ai.datatower.analytics.network;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import ai.datatower.analytics.utils.LogUtils;
class HttpUtils {
/**
* HTTP 状态码 307
*/
private static final int HTTP_307 = 307;
static boolean needRedirects(int responseCode) {
return responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HTTP_307;
}
static String getLocation(HttpURLConnection connection, String path) throws MalformedURLException {
if (connection == null || TextUtils.isEmpty(path)) {
return null;
}
String location = connection.getHeaderField("Location");
if (TextUtils.isEmpty(location)) {
location = connection.getHeaderField("location");
}
if (TextUtils.isEmpty(location)) {
return null;
}
if (!(location.startsWith("http://") || location
.startsWith("https://"))) {
//某些时候会省略 host,只返回后面的 path,所以需要补全 url
URL originUrl = new URL(path);
location = originUrl.getProtocol() + "://"
+ originUrl.getHost() + location;
}
return location;
}
static String getRetString(InputStream is) {
String buf;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
buf = sb.toString();
return buf;
} catch (Exception e) {
LogUtils.printStackTrace(e);
} finally {
if (reader != null) {
try {
reader.close();
reader = null;
} catch (IOException e) {
LogUtils.printStackTrace(e);
}
}
if (is != null) {
try {
is.close();
is = null;
} catch (IOException e) {
LogUtils.printStackTrace(e);
}
}
}
return "";
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/network/RealRequest.java
|
/*
* Created by chenru on 2020/06/22.
* Copyright 2015-2020 Sensors Data 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 ai.datatower.analytics.network;
import android.text.TextUtils;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import ai.datatower.analytics.utils.LogUtils;
class RealRequest {
private static final String TAG = "HttpRequest";
private static final int CONNECT_TIMEOUT = 30000;
private static final int READ_TIMEOUT = 30000;
private static String sRequestURL;
/**
* GET 请求
*
* @param requestURL 请求 url
* @param headerMap 请求头键值对
* @return RealResponse 返回的 Response 信息
*/
RealResponse getData(String requestURL, Map<String, String> headerMap) {
try {
// LogUtils.i(TAG,String.format("url:%s\nmethod:GET", requestURL));
sRequestURL = requestURL;
HttpURLConnection conn;
conn = getHttpURLConnection(requestURL, "GET");
if (headerMap != null) {
setHeader(conn, headerMap);
}
conn.connect();
return getRealResponse(conn);
} catch (Exception e) {
return getExceptionResponse(e);
}
}
/**
* POST 请求
*
* @param requestURL 请求 url
* @param body 请求 body 信息
* @param bodyType 请求的 Content-Type
* @param headerMap 请求头键值对
* @return RealResponse 返回的 Response 信息
*/
RealResponse postData(String requestURL, String body, String bodyType, Map<String, String> headerMap) {
BufferedWriter writer = null;
try {
HttpURLConnection conn;
sRequestURL = requestURL;
// LogUtils.i(TAG, String.format("url:%s\nparams:%s\nmethod:POST", requestURL, body));
conn = getHttpURLConnection(requestURL, "POST");
conn.setDoOutput(true);
conn.setUseCaches(false);
if (!TextUtils.isEmpty(bodyType)) {
conn.setRequestProperty("Content-Type", bodyType);
}
if (headerMap != null) {
setHeader(conn, headerMap);
}
conn.connect();
if (!TextUtils.isEmpty(body)) {
writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
writer.write(body);
writer.flush();
}
return getRealResponse(conn);
} catch (Exception e) {
return getExceptionResponse(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
LogUtils.printStackTrace(e);
}
}
}
}
/**
* 得到 HttpURLConnection 对象,并进行一些设置
*
* @param requestURL 请求的 url
* @param requestMethod 请求方法: POST,GET
* @return HttpURLConnection
* @throws IOException IOException
*/
private HttpURLConnection getHttpURLConnection(String requestURL, String requestMethod) throws IOException {
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(requestMethod);
//不使用缓存
conn.setUseCaches(false);
//设置超时时间
conn.setConnectTimeout(CONNECT_TIMEOUT);
//设置读取超时时间
conn.setReadTimeout(READ_TIMEOUT);
if (requestMethod.equals("POST")) {
//设置为 true 后才能写入参数
conn.setDoOutput(true);
}
return conn;
}
/**
* 设置请求头
*
* @param conn HttpURLConnection
* @param headerMap 请求头键值对
*/
private void setHeader(HttpURLConnection conn, Map<String, String> headerMap) {
if (headerMap != null) {
for (String key : headerMap.keySet()) {
conn.setRequestProperty(key, headerMap.get(key));
}
}
}
/**
* 当正常返回时,返回正常信息的 RealResponse 对象
*
* @param conn HttpURLConnection
* @return RealResponse 网络请求返回信息
*/
private RealResponse getRealResponse(HttpURLConnection conn) {
RealResponse response = new RealResponse();
try {
response.code = conn.getResponseCode();
if (HttpUtils.needRedirects(response.code)) {
response.location = HttpUtils.getLocation(conn, sRequestURL);
}
response.contentLength = conn.getContentLength();
response.date = conn.getDate();
// 当 ResponseCode 小于 HTTP_BAD_REQUEST(400)时,获取返回信息
if (response.code < HttpURLConnection.HTTP_BAD_REQUEST) {
response.result = HttpUtils.getRetString(conn.getInputStream());
} else {
response.errorMsg = HttpUtils.getRetString(conn.getErrorStream());
}
} catch (IOException e) {
return getExceptionResponse(e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
// LogUtils.i(TAG, response.toString());
return response;
}
/**
* 发生异常时,返回包含异常信息的 RealResponse 对象
*
* @return RealResponse 异常信息
*/
private RealResponse getExceptionResponse(Exception e) {
RealResponse response = new RealResponse();
response.exception = e;
response.errorMsg = e.getMessage();
return response;
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/network/RealResponse.java
|
/*
* Created by chenru on 2020/06/22.
* Copyright 2015-2020 Sensors Data 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 ai.datatower.analytics.network;
import androidx.annotation.NonNull;
import java.util.Locale;
public class RealResponse {
public String result;
public String errorMsg;
public String location;
public int code;
public long contentLength;
public long date;
public Exception exception;
@NonNull
@Override
public String toString() {
return String.format(Locale.getDefault(), "code:%d\nresult:%s\nlocation:%s\nerrorMsg:%s\nexception:%s",
code, result, location, errorMsg,
exception == null ? "" : exception.getMessage());
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/network/RemoteService.java
|
/*
* Copyright (C) 2022 ThinkingData
*/
package ai.datatower.analytics.network;
import java.io.IOException;
import java.util.Map;
import javax.net.ssl.SSLSocketFactory;
/**
* RemoteService.
* */
public interface RemoteService {
String performRequest(String endpointUrl, String params,
boolean debug, SSLSocketFactory sslSocketFactory,
final Map<String, String> extraHeaders)
throws IOException, DTHttpException;
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/network/RequestHelper.java
|
/*
* Created by chenru on 2020/06/22.
* Copyright 2015-2020 Sensors Data 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 ai.datatower.analytics.network;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static java.net.HttpURLConnection.HTTP_OK;
import android.text.TextUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
public class RequestHelper {
//重定向 URL
private boolean isRedirected = false;
private RequestHelper() {
}
/**
* 网络请求
*
* @param url url
* @param paramsMap 键值对参数
* @param headerMap 请求头键值对
* @param retryCount 重试次数
* @param callBack 请求回调
*/
private RequestHelper(HttpMethod method, String url, Map<String, String> paramsMap, Map<String, String> headerMap, int retryCount, HttpCallback callBack) {
switch (method) {
case GET_ASYNC:
urlHttpGet(url, paramsMap, headerMap, retryCount, callBack);
break;
case POST_ASYNC:
urlHttpPost(url, paramsMap, "", headerMap, retryCount, callBack);
break;
}
}
/**
* POST 请求
*
* @param url url
* @param jsonData json 格式参数
* @param headerMap 请求头键值对
* @param retryCount 重试次数
* @param callBack 请求回调
*/
private RequestHelper(String url, String jsonData, Map<String, String> headerMap, int retryCount, HttpCallback callBack) {
urlHttpPost(url, null, jsonData, headerMap, retryCount, callBack);
}
/**
* GET 请求
*
* @param url url
* @param paramsMap 键值对参数
* @param headerMap 请求头键值对
* @param retryCount 重试次数
* @param callBack 请求回调
*/
private void urlHttpGet(final String url, final Map<String, String> paramsMap, final Map<String, String> headerMap, final int retryCount, final HttpCallback callBack) {
final int requestCount = retryCount - 1;
HttpTaskManager.execute(new Runnable() {
@Override
public void run() {
RealResponse response = new RealRequest().getData(getUrl(url, paramsMap), headerMap);
if (response.code == HTTP_OK || response.code == HTTP_NO_CONTENT) {
if (callBack != null) {
callBack.onSuccess(response);
}
} else if (!isRedirected && HttpUtils.needRedirects(response.code)) {
isRedirected = true;
urlHttpGet(response.location, paramsMap, headerMap, retryCount, callBack);
} else {
if (requestCount != 0) {
urlHttpGet(url, paramsMap, headerMap, requestCount, callBack);
} else {
if (callBack != null) {
callBack.onError(response);
}
}
}
}
});
}
/**
* POST 请求
*
* @param url url
* @param paramsMap 键值对参数
* @param jsonData json 格式参数
* @param headerMap 请求头键值对
* @param retryCount 重试次数
* @param callBack 请求回调
*/
private void urlHttpPost(final String url, final Map<String, String> paramsMap,
final String jsonData, final Map<String, String> headerMap,
final int retryCount, final HttpCallback callBack) {
final int requestCount = retryCount - 1;
HttpTaskManager.execute(new Runnable() {
@Override
public void run() {
RealResponse response = new RealRequest().postData(url, getPostBody(paramsMap, jsonData), getPostBodyType(paramsMap, jsonData), headerMap);
if (response.code == HTTP_OK || response.code == HTTP_NO_CONTENT) {
if (callBack != null) {
callBack.onSuccess(response);
}
} else if (!isRedirected && HttpUtils.needRedirects(response.code)) {
isRedirected = true;
urlHttpPost(response.location, paramsMap, jsonData, headerMap, retryCount, callBack);
} else {
if (requestCount != 0) {
urlHttpPost(url, paramsMap, jsonData, headerMap, requestCount, callBack);
} else {
if (callBack != null) {
callBack.onError(response);
}
}
}
}
});
}
private RealResponse urlHttpPostSync(final String url, final Map<String, String> paramsMap,
final String jsonData, final Map<String, String> headerMap,
final int retryCount) {
final int requestCount = retryCount - 1;
RealResponse response = new RealRequest().postData(url, getPostBody(paramsMap, jsonData), getPostBodyType(paramsMap, jsonData), headerMap);
if (response.code == HTTP_OK || response.code == HTTP_NO_CONTENT) {
return response;
} else if (!isRedirected && HttpUtils.needRedirects(response.code)) {
isRedirected = true;
return urlHttpPostSync(response.location, paramsMap, jsonData, headerMap, retryCount);
} else {
if (requestCount != 0) {
return urlHttpPostSync(url, paramsMap, jsonData, headerMap, requestCount);
} else {
return null;
}
}
}
private RealResponse urlHttpGetSync(final String url, final Map<String, String> paramsMap, final Map<String, String> headerMap, final int retryCount) {
final int requestCount = retryCount - 1;
RealResponse response = new RealRequest().getData(getUrl(url, paramsMap), headerMap);
if (response.code == HTTP_OK || response.code == HTTP_NO_CONTENT) {
return response;
} else if (!isRedirected && HttpUtils.needRedirects(response.code)) {
isRedirected = true;
return urlHttpGetSync(response.location, paramsMap, headerMap, retryCount);
} else {
if (requestCount != 0) {
return urlHttpGetSync(url, paramsMap, headerMap, requestCount);
} else {
return null;
}
}
}
/**
* GET 请求 url 拼接
*
* @param path 请求地址
* @param paramsMap 参数键值对参数
* @return GET 请求 url 链接
*/
private String getUrl(String path, Map<String, String> paramsMap) {
if (path != null && paramsMap != null) {
if (!path.contains("?")) {
path = path + "?";
} else {
path = path + ("&");
}
for (String key : paramsMap.keySet()) {
path = path + key + "=" + paramsMap.get(key) + "&";
}
path = path.substring(0, path.length() - 1);
}
return path;
}
/**
* 根据参数得到 body
*
* @param params 键值对参数
* @param jsonStr json 格式参数
* @return 请求 body
*/
private String getPostBody(Map<String, String> params, String jsonStr) {
if (params != null) {
return getPostBodyFormParamsMap(params);
} else if (!TextUtils.isEmpty(jsonStr)) {
return jsonStr;
}
return null;
}
/**
* 根据键值对参数得到 body
*
* @param params 键值对参数
* @return 请求 body
*/
private String getPostBodyFormParamsMap(Map<String, String> params) {
if (params != null) {
StringBuilder result = new StringBuilder();
boolean first = true;
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first) {
first = false;
} else {
result.append("&");
}
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
} catch (UnsupportedEncodingException e) {
return null;
}
}
return null;
}
/**
* 获取请求的 Content-Type
*
* @param paramsMap 请求参数
* @param jsonStr 请求参数 json 字符串
* @return Content-Type
*/
private String getPostBodyType(Map<String, String> paramsMap, String jsonStr) {
if (paramsMap != null) {
return null;
} else if (!TextUtils.isEmpty(jsonStr)) {
return "application/json;charset=utf-8";
}
return null;
}
public static class Builder {
private HttpMethod httpMethod;
private String httpUrl;
private Map<String, String> paramsMap;
private String jsonData;
private Map<String, String> headerMap;
private HttpCallback callBack;
private int retryCount = 1;
public Builder(HttpMethod method, String url) {
this.httpMethod = method;
this.httpUrl = url;
}
public Builder params(Map<String, String> paramsMap) {
this.paramsMap = paramsMap;
return this;
}
public Builder jsonData(String data) {
this.jsonData = data;
return this;
}
public Builder header(Map<String, String> headerMap) {
this.headerMap = headerMap;
return this;
}
public Builder callback(HttpCallback callBack) {
this.callBack = callBack;
return this;
}
public Builder retryCount(int retryCount) {
this.retryCount = retryCount;
return this;
}
public void execute() {
if (httpMethod == HttpMethod.POST_ASYNC && paramsMap == null) {
new RequestHelper(httpUrl, jsonData, headerMap, retryCount, callBack);
} else {
new RequestHelper(httpMethod, httpUrl, paramsMap, headerMap, retryCount, callBack);
}
}
public RealResponse executeSync() {
if (httpMethod == HttpMethod.POST_SYNC) {
return new RequestHelper().urlHttpPostSync(httpUrl, paramsMap, jsonData, headerMap, retryCount);
} else if (httpMethod == HttpMethod.GET_SYNC){
return new RequestHelper().urlHttpGetSync(httpUrl, paramsMap, headerMap, retryCount);
}else {
return new RealResponse();
}
}
}
/**
* 发生异常时,返回包含异常信息的 RealResponse 对象
*
* @return RealResponse 异常信息
*/
private RealResponse getExceptionResponse(Exception e) {
RealResponse response = new RealResponse();
response.exception = e;
response.errorMsg = e.getMessage();
return response;
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/network/ResponseStatus.java
|
/*
* Created by chenru on 2020/06/22.
* Copyright 2015-2020 Sensors Data 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 ai.datatower.analytics.network;
public enum ResponseStatus {
/**
* 成功
*/
SUCCESS,
/**
* 解析错误
*/
PARSE_ERROR,
/**
* 未查询到数据
*/
NO_QUERY,
/**
* 请求获取参数失败
*/
GET_PARAMS_FAILED
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/taskqueue/AsyncTaskQueue.java
|
package ai.datatower.analytics.taskqueue;
import androidx.annotation.NonNull;
import java.lang.ref.WeakReference;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import ai.datatower.analytics.utils.LogUtils;
import kotlin.coroutines.CoroutineContext;
import kotlinx.coroutines.CoroutineDispatcher;
import kotlinx.coroutines.CoroutineScope;
public class AsyncTaskQueue extends CoroutineDispatcher implements CoroutineScope {
private String mName;
private ThreadPoolExecutor mPool;
public Thread activeThread;
protected long taskBeginTime = 0;
protected long taskEndTime = 0;
static String tag = "PerfLog";
public void postTask(Runnable task) {
mPool.execute(new Runnable() {
@Override
public void run() {
taskWillRun();
task.run();
taskDidRun();
}
});
}
void taskWillRun() {
taskBeginTime = System.currentTimeMillis();
}
void taskDidRun() {
taskEndTime = System.currentTimeMillis();
if (taskEndTime - taskBeginTime > 3000) {
LogUtils.d(tag, "task time out in queue" + this.mName);
}
}
public int taskCount() {
synchronized (mPool) {
return mPool.getQueue().size();
}
}
public Thread getCurrentThread() {
return activeThread;
}
AsyncTaskQueue(String name) {
mName = name;
mPool = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
new ThreadFactoryWithName(mName, this));
}
@Override
public void dispatch(@NonNull CoroutineContext coroutineContext, @NonNull Runnable runnable) {
postTask(runnable);
}
@NonNull
@Override
public CoroutineContext getCoroutineContext() {
return (CoroutineContext) this;
}
static class ThreadFactoryWithName implements ThreadFactory {
private final String name;
private WeakReference<AsyncTaskQueue> mHolder;
ThreadFactoryWithName(String name, AsyncTaskQueue holder) {
this.name = name;
this.mHolder = new WeakReference(holder);
}
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, name);
thread.setUncaughtExceptionHandler((t, e) -> LogUtils.e(e.getMessage()));
mHolder.get().activeThread = thread;
return thread;
}
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/taskqueue/DBQueue.java
|
package ai.datatower.analytics.taskqueue;
public class DBQueue extends AsyncTaskQueue {
private volatile static DBQueue singleton; //1:volatile修饰
public static DBQueue get() {
if (singleton == null) { //2:减少不要同步,优化性能
synchronized (DBQueue.class) { // 3:同步,线程安全
if (singleton == null) {
singleton = new DBQueue(); //4:创建singleton 对象
}
}
}
return singleton;
}
private DBQueue() {
super("DBQueue");
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/taskqueue/DataUploadQueue.java
|
package ai.datatower.analytics.taskqueue;
public class DataUploadQueue extends AsyncTaskQueue {
private volatile static DataUploadQueue singleton; //1:volatile修饰
public static DataUploadQueue get() {
if (singleton == null) { //2:减少不要同步,优化性能
synchronized (DataUploadQueue.class) { // 3:同步,线程安全
if (singleton == null) {
singleton = new DataUploadQueue(); //4:创建singleton 对象
}
}
}
return singleton;
}
private DataUploadQueue() {
super("DataUploadQueue");
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/taskqueue/MainQueue.java
|
package ai.datatower.analytics.taskqueue;
public class MainQueue extends AsyncTaskQueue {
private volatile static MainQueue singleton; //1:volatile修饰
public static MainQueue get() {
if (singleton == null) { //2:减少不要同步,优化性能
synchronized (MainQueue.class) { // 3:同步,线程安全
if (singleton == null) {
singleton = new MainQueue(); //4:创建singleton 对象
}
}
}
return singleton;
}
private MainQueue() {
super("MainQueue");
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/AdtUtil.java
|
// Copyright 2020 ADTIMING TECHNOLOGY COMPANY LIMITED
// Licensed under the GNU Lesser General Public License Version 3
package ai.datatower.analytics.utils;
import android.app.Application;
import java.lang.ref.SoftReference;
/**
*
*/
public class AdtUtil {
private SoftReference<Application> mContext = null;
private AdtUtil() {
}
private static final class Holder {
private static final AdtUtil INSTANCE = new AdtUtil();
}
public static AdtUtil getInstance() {
return Holder.INSTANCE;
}
public Application getApplicationContext() {
if (mContext == null || mContext.get() == null) {
Application application = currentApplication();
if (application == null) {
application = getInitialApplication();
}
mContext = new SoftReference<>(application);
}
return mContext.get();
}
private Application currentApplication() {
Application application = null;
try {
application = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null, new Object[]{});
} catch (Throwable ignored) {
}
return application;
}
private Application getInitialApplication() {
Application application = null;
try {
application = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null, new Object[]{});
} catch (Throwable ignored) {
}
return application;
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/AppLifecycleHelper.java
|
package ai.datatower.analytics.utils;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
public class AppLifecycleHelper {
private OnAppStatusListener mOnAppStatusListener;
public AppLifecycleHelper() {
}
/**
* 注册状态监听,仅在Application中使用
* @param application
* @param listener
*/
public void register(Application application, OnAppStatusListener listener){
mOnAppStatusListener = listener;
application.registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
}
public void unRegister(Application application){
application.unregisterActivityLifecycleCallbacks(activityLifecycleCallbacks);
}
private Application.ActivityLifecycleCallbacks activityLifecycleCallbacks = new Application.ActivityLifecycleCallbacks() {
//打开的Activity数量统计
private int activityStartCount = 0;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
activityStartCount++;
//数值从0变到1说明是从后台切到前台
if (activityStartCount == 1){
//从后台切到前台
if(mOnAppStatusListener != null){
mOnAppStatusListener.onAppForeground();
}
}
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
activityStartCount--;
//数值从1到0说明是从前台切到后台
if (activityStartCount == 0){
//从前台切到后台
if(mOnAppStatusListener != null){
mOnAppStatusListener.onAppBackground();
}
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
};
public interface OnAppStatusListener{
void onAppForeground();
void onAppBackground();
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/DataUtils.java
|
/*
* Created by wangzhuozhou on 2015/08/01.
* Copyright 2015-2020 Sensors Data 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 ai.datatower.analytics.utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;
public final class DataUtils {
public static String getUUID() {
SecureRandom random = new SecureRandom();
String uuid = String.valueOf(random.nextLong());
return uuid.replace("-", "");
}
public static String getSession() {
StringBuilder uuid = new StringBuilder();
for (int i = 0; i < 16; i++) {
uuid.append(Integer.toHexString(new Random().nextInt(16)));
}
return uuid.toString();
}
// 返回当前时区偏移,单位毫秒
public static double getTimezoneOffset(long time, TimeZone timeZone) {
TimeZone tz = (null == timeZone) ? TimeZone.getDefault() : timeZone;
return tz.getOffset(time) / (1000.0 * 60 * 60);
}
public static void mergeJSONObject(final JSONObject source, JSONObject dest, TimeZone timeZone)
throws JSONException {
Iterator<String> sourceIterator = source.keys();
while (sourceIterator.hasNext()) {
String key = sourceIterator.next();
Object value = source.get(key);
if (value instanceof Date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA);
if (null != timeZone) {
dateFormat.setTimeZone(timeZone);
}
dest.put(key, dateFormat.format((Date) value));
} else if (value instanceof JSONArray) {
dest.put(key, formatJSONArray((JSONArray) value, timeZone));
} else if (value instanceof JSONObject) {
dest.put(key, formatJSONObject((JSONObject) value, timeZone));
} else {
dest.put(key, value);
}
}
}
public static JSONObject formatJSONObject(JSONObject jsonObject, TimeZone timeZone) {
JSONObject result = new JSONObject();
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = null;
try {
value = jsonObject.get(key);
if (value instanceof Date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA);
if (null != timeZone) {
dateFormat.setTimeZone(timeZone);
}
result.put(key, dateFormat.format((Date) value));
} else if (value instanceof JSONArray) {
result.put(key, formatJSONArray((JSONArray) value, timeZone));
} else if (value instanceof JSONObject) {
result.put(key, formatJSONObject((JSONObject) value, timeZone));
} else {
result.put(key, value);
}
} catch (JSONException exception) {
exception.printStackTrace();
}
}
return result;
}
public static JSONArray formatJSONArray(JSONArray jsonArr, TimeZone timeZone) {
JSONArray result = new JSONArray();
for (int i = 0; i < jsonArr.length(); i++) {
Object value = jsonArr.opt(i);
if (value != null) {
if (value instanceof Date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.CHINA);
if (null != timeZone) {
dateFormat.setTimeZone(timeZone);
}
result.put(dateFormat.format((Date) value));
} else if (value instanceof JSONArray) {
result.put(formatJSONArray((JSONArray) value, timeZone));
} else if (value instanceof JSONObject) {
JSONObject newObject = formatJSONObject((JSONObject) value, timeZone);
result.put(newObject);
} else {
result.put(value);
}
}
}
return result;
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/EmulatorDetector.java
|
package ai.datatower.analytics.utils;
import android.text.TextUtils;
import java.lang.reflect.Method;
public class EmulatorDetector {
/**
* Detects if app is currenly running on emulator, or real device.
*
* @return true for emulator, false for real devices
*/
public static boolean isEmulator() {
if (mayOnEmulatorViaQEMU()) {
return true;
}
return isEmulatorFromAbi();
}
private static boolean mayOnEmulatorViaQEMU() {
String qemu = getProp("ro.kernel.qemu");
return "1".equals(qemu);
}
private static boolean isEmulatorFromAbi() {
String abi = getProp("ro.product.cpu.abi");
if (abi == null) return false;
return !TextUtils.isEmpty(abi) && abi.contains("x86");
}
private static String getProp(String property) {
try {
Class<?> systemProperties = Class.forName("android.os.SystemProperties");
Method method = systemProperties.getMethod("get", String.class);
Object[] params = new Object[1];
params[0] = property;
return (String) method.invoke(systemProperties, params);
} catch (Exception e) {
return null;
}
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/JsonUtils.java
|
package ai.datatower.analytics.utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
public final class JsonUtils {
private static final byte TYPE_BOOLEAN = 0x00;
private static final byte TYPE_INT = 0x01;
private static final byte TYPE_LONG = 0x02;
private static final byte TYPE_DOUBLE = 0x03;
private static final byte TYPE_STRING = 0x04;
private static final byte TYPE_JSON_OBJECT = 0x05;
private static final byte TYPE_JSON_ARRAY = 0x06;
private JsonUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
public static boolean getBoolean(final JSONObject jsonObject,
final String key) {
return getBoolean(jsonObject, key, false);
}
public static boolean getBoolean(final JSONObject jsonObject,
final String key,
final boolean defaultValue) {
return getValueByType(jsonObject, key, defaultValue, TYPE_BOOLEAN);
}
public static boolean getBoolean(final String json,
final String key) {
return getBoolean(json, key, false);
}
public static boolean getBoolean(final String json,
final String key,
final boolean defaultValue) {
return getValueByType(json, key, defaultValue, TYPE_BOOLEAN);
}
public static int getInt(final JSONObject jsonObject,
final String key) {
return getInt(jsonObject, key, -1);
}
public static int getInt(final JSONObject jsonObject,
final String key,
final int defaultValue) {
return getValueByType(jsonObject, key, defaultValue, TYPE_INT);
}
public static int getInt(final String json,
final String key) {
return getInt(json, key, -1);
}
public static int getInt(final String json,
final String key,
final int defaultValue) {
return getValueByType(json, key, defaultValue, TYPE_INT);
}
public static long getLong(final JSONObject jsonObject,
final String key) {
return getLong(jsonObject, key, -1);
}
public static long getLong(final JSONObject jsonObject,
final String key,
final long defaultValue) {
return getValueByType(jsonObject, key, defaultValue, TYPE_LONG);
}
public static long getLong(final String json,
final String key) {
return getLong(json, key, -1);
}
public static long getLong(final String json,
final String key,
final long defaultValue) {
return getValueByType(json, key, defaultValue, TYPE_LONG);
}
public static double getDouble(final JSONObject jsonObject,
final String key) {
return getDouble(jsonObject, key, -1);
}
public static double getDouble(final JSONObject jsonObject,
final String key,
final double defaultValue) {
return getValueByType(jsonObject, key, defaultValue, TYPE_DOUBLE);
}
public static double getDouble(final String json,
final String key) {
return getDouble(json, key, -1);
}
public static double getDouble(final String json,
final String key,
final double defaultValue) {
return getValueByType(json, key, defaultValue, TYPE_DOUBLE);
}
public static String getString(final JSONObject jsonObject,
final String key) {
return getString(jsonObject, key, "");
}
public static String getString(final JSONObject jsonObject,
final String key,
final String defaultValue) {
return getValueByType(jsonObject, key, defaultValue, TYPE_STRING);
}
public static String getString(final String json,
final String key) {
return getString(json, key, "");
}
public static String getString(final String json,
final String key,
final String defaultValue) {
return getValueByType(json, key, defaultValue, TYPE_STRING);
}
public static JSONObject getJSONObject(final JSONObject jsonObject,
final String key,
final JSONObject defaultValue) {
return getValueByType(jsonObject, key, defaultValue, TYPE_JSON_OBJECT);
}
public static JSONObject getJSONObject(final String json,
final String key,
final JSONObject defaultValue) {
return getValueByType(json, key, defaultValue, TYPE_JSON_OBJECT);
}
public static JSONArray getJSONArray(final JSONObject jsonObject,
final String key,
final JSONArray defaultValue) {
return getValueByType(jsonObject, key, defaultValue, TYPE_JSON_ARRAY);
}
public static JSONArray getJSONArray(final String json,
final String key,
final JSONArray defaultValue) {
return getValueByType(json, key, defaultValue, TYPE_JSON_ARRAY);
}
private static <T> T getValueByType(final JSONObject jsonObject,
final String key,
final T defaultValue,
final byte type) {
if (jsonObject == null || key == null || key.length() == 0) {
return defaultValue;
}
try {
Object ret;
if (type == TYPE_BOOLEAN) {
ret = jsonObject.getBoolean(key);
} else if (type == TYPE_INT) {
ret = jsonObject.getInt(key);
} else if (type == TYPE_LONG) {
ret = jsonObject.getLong(key);
} else if (type == TYPE_DOUBLE) {
ret = jsonObject.getDouble(key);
} else if (type == TYPE_STRING) {
ret = jsonObject.getString(key);
} else if (type == TYPE_JSON_OBJECT) {
ret = jsonObject.getJSONObject(key);
} else if (type == TYPE_JSON_ARRAY) {
ret = jsonObject.getJSONArray(key);
} else {
return defaultValue;
}
//noinspection unchecked
return (T) ret;
} catch (JSONException e) {
e.printStackTrace();
return defaultValue;
}
}
private static <T> T getValueByType(final String json,
final String key,
final T defaultValue,
final byte type) {
if (json == null || json.length() == 0
|| key == null || key.length() == 0) {
return defaultValue;
}
try {
return getValueByType(new JSONObject(json), key, defaultValue, type);
} catch (JSONException e) {
e.printStackTrace();
return defaultValue;
}
}
public static String formatJson(final String json) {
return formatJson(json, 4);
}
public static String formatJson(final String json, final int indentSpaces) {
try {
for (int i = 0, len = json.length(); i < len; i++) {
char c = json.charAt(i);
if (c == '{') {
return new JSONObject(json).toString(indentSpaces);
} else if (c == '[') {
return new JSONArray(json).toString(indentSpaces);
} else if (!Character.isWhitespace(c)) {
return json;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
public static Object wrap(Object o) {
if (o == null) {
return JSONObject.NULL;
}
if (o instanceof JSONArray || o instanceof JSONObject) {
return o;
}
if (o.equals(JSONObject.NULL)) {
return o;
}
try {
if (o instanceof Collection) {
return new JSONArray((Collection) o);
} else if (o.getClass().isArray()) {
return toJSONArray(o);
}
if (o instanceof Map) {
return new JSONObject((Map) o);
}
if (o instanceof Boolean
|| o instanceof Byte
|| o instanceof Character
|| o instanceof Double
|| o instanceof Float
|| o instanceof Integer
|| o instanceof Long
|| o instanceof Short
|| o instanceof String) {
return o;
}
if (o.getClass().getPackage().getName().startsWith("java.")) {
return o.toString();
}
} catch (Exception ignored) {
//ignored
}
return null;
}
public static JSONArray toJSONArray(Object array) throws JSONException {
JSONArray result = new JSONArray();
if (!array.getClass().isArray()) {
throw new JSONException("Not a primitive array: " + array.getClass());
}
final int length = Array.getLength(array);
for (int i = 0; i < length; ++i) {
result.put(wrap(Array.get(array, i)));
}
return result;
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/LogUtils.java
|
package ai.datatower.analytics.utils;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.IntDef;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public final class LogUtils {
public static final int V = Log.VERBOSE;
public static final int D = Log.DEBUG;
public static final int I = Log.INFO;
public static final int W = Log.WARN;
public static final int E = Log.ERROR;
public static final int A = Log.ASSERT;
@IntDef({V, D, I, W, E, A})
@Retention(RetentionPolicy.SOURCE)
public @interface TYPE {
}
private static final char[] T = new char[]{'V', 'D', 'I', 'W', 'E', 'A'};
private static final int FILE = 0x10;
private static final int JSON = 0x20;
private static final int XML = 0x30;
private static final String FILE_SEP = System.getProperty("file.separator");
private static final String LINE_SEP = System.getProperty("line.separator");
private static final String TOP_CORNER = "┌";
private static final String MIDDLE_CORNER = "├";
private static final String LEFT_BORDER = "│ ";
private static final String BOTTOM_CORNER = "└";
private static final String SIDE_DIVIDER =
"────────────────────────────────────────────────────────";
private static final String MIDDLE_DIVIDER =
"┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄";
private static final String TOP_BORDER = TOP_CORNER + SIDE_DIVIDER + SIDE_DIVIDER;
private static final String MIDDLE_BORDER = MIDDLE_CORNER + MIDDLE_DIVIDER + MIDDLE_DIVIDER;
private static final String BOTTOM_BORDER = BOTTOM_CORNER + SIDE_DIVIDER + SIDE_DIVIDER;
private static final int MAX_LEN = 1100;// fit for Chinese character
private static final String NOTHING = "log nothing";
private static final String NULL = "null";
private static final String ARGS = "args";
private static final String PLACEHOLDER = " ";
private static final Config CONFIG = new Config();
private static SimpleDateFormat simpleDateFormat;
private static final HashMap<Class, IFormatter> I_FORMATTER_MAP = new HashMap<>();
private LogUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
public static Config getConfig() {
return CONFIG;
}
public static void printStackTrace(final Object... contents) {
log(E, CONFIG.getGlobalTag(), contents);
}
public static void v(final Object... contents) {
log(V, CONFIG.getGlobalTag(), contents);
}
public static void v(final String tag, final Object... contents) {
log(V, tag, contents);
}
public static void d(final Object... contents) {
log(D, CONFIG.getGlobalTag(), contents);
}
public static void d(final String tag, final Object... contents) {
log(D, tag, contents);
}
public static void i(final Object... contents) {
log(I, CONFIG.getGlobalTag(), contents);
}
public static void i(final String tag, final Object... contents) {
log(I, tag, contents);
}
public static void w(final Object... contents) {
log(W, CONFIG.getGlobalTag(), contents);
}
public static void w(final String tag, final Object... contents) {
log(W, tag, contents);
}
public static void e(final Object... contents) {
log(E, CONFIG.getGlobalTag(), contents);
}
public static void e(final String tag, final Object... contents) {
log(E, tag, contents);
}
public static void a(final Object... contents) {
log(A, CONFIG.getGlobalTag(), contents);
}
public static void a(final String tag, final Object... contents) {
log(A, tag, contents);
}
public static void file(final Object content) {
log(FILE | D, CONFIG.getGlobalTag(), content);
}
public static void file(@TYPE final int type, final Object content) {
log(FILE | type, CONFIG.getGlobalTag(), content);
}
public static void file(final String tag, final Object content) {
log(FILE | D, tag, content);
}
public static void file(@TYPE final int type, final String tag, final Object content) {
log(FILE | type, tag, content);
}
public static void json(final Object content) {
log(JSON | D, CONFIG.getGlobalTag(), content);
}
public static void json(@TYPE final int type, final Object content) {
log(JSON | type, CONFIG.getGlobalTag(), content);
}
public static void json(final String tag, final Object content) {
log(JSON | D, tag, content);
}
public static void json(@TYPE final int type, final String tag, final Object content) {
log(JSON | type, tag, content);
}
public static void xml(final String content) {
log(XML | D, CONFIG.getGlobalTag(), content);
}
public static void xml(@TYPE final int type, final String content) {
log(XML | type, CONFIG.getGlobalTag(), content);
}
public static void xml(final String tag, final String content) {
log(XML | D, tag, content);
}
public static void xml(@TYPE final int type, final String tag, final String content) {
log(XML | type, tag, content);
}
public static void log(final int type, final String tag, final Object... contents) {
if (!CONFIG.isLogSwitch()) return;
final int type_low = type & 0x0f, type_high = type & 0xf0;
if (CONFIG.isLog2ConsoleSwitch() || type_high == FILE) {
if (type_low < CONFIG.mConsoleFilter ) return;
final TagHead tagHead = processTagAndHead(tag);
final String body = processBody(type_high, contents);
if (CONFIG.mOnConsoleOutputListener != null) {
CONFIG.mOnConsoleOutputListener.onConsoleOutput(type, tag, body);
}
if (CONFIG.isLog2ConsoleSwitch() && type_high != FILE && type_low >= CONFIG.mConsoleFilter) {
print2Console(type_low, tagHead.tag, tagHead.consoleHead, body);
}
}
}
private static TagHead processTagAndHead(String tag) {
if (!CONFIG.mTagIsSpace && !CONFIG.isLogHeadSwitch()) {
tag = CONFIG.getGlobalTag();
} else {
final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
final int stackIndex = 3 + CONFIG.getStackOffset();
if (stackIndex >= stackTrace.length) {
StackTraceElement targetElement = stackTrace[3];
final String fileName = getFileName(targetElement);
if (CONFIG.mTagIsSpace && isSpace(tag)) {
int index = fileName.indexOf('.');// Use proguard may not find '.'.
tag = index == -1 ? fileName : fileName.substring(0, index);
}
return new TagHead(tag, null, ": ");
}
StackTraceElement targetElement = stackTrace[stackIndex];
final String fileName = getFileName(targetElement);
if (CONFIG.mTagIsSpace && isSpace(tag)) {
int index = fileName.indexOf('.');// Use proguard may not find '.'.
tag = index == -1 ? fileName : fileName.substring(0, index);
}
if (CONFIG.isLogHeadSwitch()) {
String tName = Thread.currentThread().getName();
final String head = new Formatter()
.format("%s, %s.%s(%s:%d)",
tName,
targetElement.getClassName(),
targetElement.getMethodName(),
fileName,
targetElement.getLineNumber())
.toString();
final String fileHead = " [" + head + "]: ";
if (CONFIG.getStackDeep() <= 1) {
return new TagHead(tag, new String[]{head}, fileHead);
} else {
final String[] consoleHead =
new String[Math.min(
CONFIG.getStackDeep(),
stackTrace.length - stackIndex
)];
consoleHead[0] = head;
int spaceLen = tName.length() + 2;
String space = new Formatter().format("%" + spaceLen + "s", "").toString();
for (int i = 1, len = consoleHead.length; i < len; ++i) {
targetElement = stackTrace[i + stackIndex];
consoleHead[i] = new Formatter()
.format("%s%s.%s(%s:%d)",
space,
targetElement.getClassName(),
targetElement.getMethodName(),
getFileName(targetElement),
targetElement.getLineNumber())
.toString();
}
return new TagHead(tag, consoleHead, fileHead);
}
}
}
return new TagHead(tag, null, ": ");
}
private static String getFileName(final StackTraceElement targetElement) {
String fileName = targetElement.getFileName();
if (fileName != null) return fileName;
// If name of file is null, should add
// "-keepattributes SourceFile,LineNumberTable" in proguard file.
String className = targetElement.getClassName();
String[] classNameInfo = className.split("\\.");
if (classNameInfo.length > 0) {
className = classNameInfo[classNameInfo.length - 1];
}
int index = className.indexOf('$');
if (index != -1) {
className = className.substring(0, index);
}
return className + ".java";
}
private static String processBody(final int type, final Object... contents) {
String body = NULL;
if (contents != null) {
if (contents.length == 1) {
body = formatObject(type, contents[0]);
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0, len = contents.length; i < len; ++i) {
Object content = contents[i];
sb.append(ARGS)
.append("[")
.append(i)
.append("]")
.append(" = ")
.append(formatObject(content))
.append(LINE_SEP);
}
body = sb.toString();
}
}
return body.length() == 0 ? NOTHING : body;
}
private static String formatObject(int type, Object object) {
if (object == null) return NULL;
if (type == JSON) return LogFormatter.object2String(object, JSON);
if (type == XML) return LogFormatter.object2String(object, XML);
return formatObject(object);
}
private static String formatObject(Object object) {
if (object == null) return NULL;
if (!I_FORMATTER_MAP.isEmpty()) {
IFormatter iFormatter = I_FORMATTER_MAP.get(getClassFromObject(object));
if (iFormatter != null) {
//noinspection unchecked
return iFormatter.format(object);
}
}
return LogFormatter.object2String(object);
}
private static void print2Console(final int type,
final String tag,
final String[] head,
final String msg) {
if (CONFIG.isSingleTagSwitch()) {
printSingleTagMsg(type, tag, processSingleTagMsg(type, tag, head, msg));
} else {
printBorder(type, tag, true);
printHead(type, tag, head);
printMsg(type, tag, msg);
printBorder(type, tag, false);
}
}
private static void printBorder(final int type, final String tag, boolean isTop) {
if (CONFIG.isLogBorderSwitch()) {
print2Console(type, tag, isTop ? TOP_BORDER : BOTTOM_BORDER);
}
}
private static void printHead(final int type, final String tag, final String[] head) {
if (head != null) {
for (String aHead : head) {
print2Console(type, tag, CONFIG.isLogBorderSwitch() ? LEFT_BORDER + aHead : aHead);
}
if (CONFIG.isLogBorderSwitch()) print2Console(type, tag, MIDDLE_BORDER);
}
}
private static void printMsg(final int type, final String tag, final String msg) {
int len = msg.length();
int countOfSub = len / MAX_LEN;
if (countOfSub > 0) {
int index = 0;
for (int i = 0; i < countOfSub; i++) {
printSubMsg(type, tag, msg.substring(index, index + MAX_LEN));
index += MAX_LEN;
}
if (index != len) {
printSubMsg(type, tag, msg.substring(index, len));
}
} else {
printSubMsg(type, tag, msg);
}
}
private static void printSubMsg(final int type, final String tag, final String msg) {
if (!CONFIG.isLogBorderSwitch()) {
print2Console(type, tag, msg);
return;
}
StringBuilder sb = new StringBuilder();
String[] lines = msg.split(LINE_SEP);
for (String line : lines) {
print2Console(type, tag, LEFT_BORDER + line);
}
}
private static String processSingleTagMsg(final int type,
final String tag,
final String[] head,
final String msg) {
StringBuilder sb = new StringBuilder();
if (CONFIG.isLogBorderSwitch()) {
sb.append(PLACEHOLDER).append(LINE_SEP);
sb.append(TOP_BORDER).append(LINE_SEP);
if (head != null) {
for (String aHead : head) {
sb.append(LEFT_BORDER).append(aHead).append(LINE_SEP);
}
sb.append(MIDDLE_BORDER).append(LINE_SEP);
}
for (String line : msg.split(LINE_SEP)) {
sb.append(LEFT_BORDER).append(line).append(LINE_SEP);
}
sb.append(BOTTOM_BORDER);
} else {
if (head != null) {
sb.append(PLACEHOLDER).append(LINE_SEP);
for (String aHead : head) {
sb.append(aHead).append(LINE_SEP);
}
}
sb.append(msg);
}
return sb.toString();
}
private static void printSingleTagMsg(final int type, final String tag, final String msg) {
int len = msg.length();
int countOfSub = CONFIG.isLogBorderSwitch() ? (len - BOTTOM_BORDER.length()) / MAX_LEN : len / MAX_LEN;
if (countOfSub > 0) {
if (CONFIG.isLogBorderSwitch()) {
print2Console(type, tag, msg.substring(0, MAX_LEN) + LINE_SEP + BOTTOM_BORDER);
int index = MAX_LEN;
for (int i = 1; i < countOfSub; i++) {
print2Console(type, tag, PLACEHOLDER + LINE_SEP + TOP_BORDER + LINE_SEP
+ LEFT_BORDER + msg.substring(index, index + MAX_LEN)
+ LINE_SEP + BOTTOM_BORDER);
index += MAX_LEN;
}
if (index != len - BOTTOM_BORDER.length()) {
print2Console(type, tag, PLACEHOLDER + LINE_SEP + TOP_BORDER + LINE_SEP
+ LEFT_BORDER + msg.substring(index, len));
}
} else {
print2Console(type, tag, msg.substring(0, MAX_LEN));
int index = MAX_LEN;
for (int i = 1; i < countOfSub; i++) {
print2Console(type, tag,
PLACEHOLDER + LINE_SEP + msg.substring(index, index + MAX_LEN));
index += MAX_LEN;
}
if (index != len) {
print2Console(type, tag, PLACEHOLDER + LINE_SEP + msg.substring(index, len));
}
}
} else {
print2Console(type, tag, msg);
}
}
private static void print2Console(int type, String tag, String msg) {
Log.println(type, tag, msg);
}
/**
* Return whether the string is null or white space.
*
* @param s The string.
* @return {@code true}: yes<br> {@code false}: no
*/
private static boolean isSpace(final String s) {
if (s == null) return true;
for (int i = 0, len = s.length(); i < len; ++i) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
public static final class Config {
// The default storage directory of log.
private boolean mLogSwitch = true; // The switch of log.
private boolean mLog2ConsoleSwitch = true; // The logcat's switch of log.
private String mGlobalTag = ""; // The global tag of log.
private boolean mTagIsSpace = true; // The global tag is space.
private boolean mLogHeadSwitch = true; // The head's switch of log.
private boolean mLogBorderSwitch = true; // The border's switch of log.
private boolean mSingleTagSwitch = true; // The single tag of log.
private int mConsoleFilter = V; // The console's filter of log.
private int mStackDeep = 1; // The stack's deep of log.
private int mStackOffset = 0; // The stack's offset of log.
private int mSaveDays = -1; // The save days of log.
private OnConsoleOutputListener mOnConsoleOutputListener;
private Config() {
}
public final Config setLogSwitch(final boolean logSwitch) {
mLogSwitch = logSwitch;
return this;
}
public final Config setConsoleSwitch(final boolean consoleSwitch) {
mLog2ConsoleSwitch = consoleSwitch;
return this;
}
public final Config setGlobalTag(final String tag) {
if (isSpace(tag)) {
mGlobalTag = "";
mTagIsSpace = true;
} else {
mGlobalTag = tag;
mTagIsSpace = false;
}
return this;
}
public final Config setLogHeadSwitch(final boolean logHeadSwitch) {
mLogHeadSwitch = logHeadSwitch;
return this;
}
public final Config setBorderSwitch(final boolean borderSwitch) {
mLogBorderSwitch = borderSwitch;
return this;
}
public final Config setSingleTagSwitch(final boolean singleTagSwitch) {
mSingleTagSwitch = singleTagSwitch;
return this;
}
public final Config setConsoleFilter(@TYPE final int consoleFilter) {
mConsoleFilter = consoleFilter;
return this;
}
public final Config setStackDeep(@IntRange(from = 1) final int stackDeep) {
mStackDeep = stackDeep;
return this;
}
public final Config setStackOffset(@IntRange(from = 0) final int stackOffset) {
mStackOffset = stackOffset;
return this;
}
public final Config setSaveDays(@IntRange(from = 1) final int saveDays) {
mSaveDays = saveDays;
return this;
}
public final <T> Config addFormatter(final IFormatter<T> iFormatter) {
if (iFormatter != null) {
I_FORMATTER_MAP.put(getTypeClassFromParadigm(iFormatter), iFormatter);
}
return this;
}
public final Config setOnConsoleOutputListener(final OnConsoleOutputListener listener) {
mOnConsoleOutputListener = listener;
return this;
}
public final boolean isLogSwitch() {
return mLogSwitch;
}
public final boolean isLog2ConsoleSwitch() {
return mLog2ConsoleSwitch;
}
public final String getGlobalTag() {
if (isSpace(mGlobalTag)) return "";
return mGlobalTag;
}
public final boolean isLogHeadSwitch() {
return mLogHeadSwitch;
}
public final boolean isLogBorderSwitch() {
return mLogBorderSwitch;
}
public final boolean isSingleTagSwitch() {
return mSingleTagSwitch;
}
public final char getConsoleFilter() {
return T[mConsoleFilter - V];
}
public final int getStackDeep() {
return mStackDeep;
}
public final int getStackOffset() {
return mStackOffset;
}
public final int getSaveDays() {
return mSaveDays;
}
@NonNull
@Override
public String toString() {
return
LINE_SEP + "logSwitch: " + isLogSwitch()
+ LINE_SEP + "consoleSwitch: " + isLog2ConsoleSwitch()
+ LINE_SEP + "tag: " + (getGlobalTag().equals("") ? "null" : getGlobalTag())
+ LINE_SEP + "headSwitch: " + isLogHeadSwitch()
+ LINE_SEP + "borderSwitch: " + isLogBorderSwitch()
+ LINE_SEP + "singleTagSwitch: " + isSingleTagSwitch()
+ LINE_SEP + "consoleFilter: " + getConsoleFilter()
+ LINE_SEP + "stackDeep: " + getStackDeep()
+ LINE_SEP + "stackOffset: " + getStackOffset()
+ LINE_SEP + "saveDays: " + getSaveDays()
+ LINE_SEP + "formatter: " + I_FORMATTER_MAP
+ LINE_SEP + "onConsoleOutputListener: " + mOnConsoleOutputListener;
}
}
public abstract static class IFormatter<T> {
public abstract String format(T t);
}
public interface IFileWriter {
void write(String file, String content);
}
public interface OnConsoleOutputListener {
void onConsoleOutput(@TYPE int type, String tag, String content);
}
public interface OnFileOutputListener {
void onFileOutput(String filePath, String content);
}
private final static class TagHead {
String tag;
String[] consoleHead;
String fileHead;
TagHead(String tag, String[] consoleHead, String fileHead) {
this.tag = tag;
this.consoleHead = consoleHead;
this.fileHead = fileHead;
}
}
private final static class LogFormatter {
static String object2String(Object object) {
return object2String(object, -1);
}
static String object2String(Object object, int type) {
if (object.getClass().isArray()) return array2String(object);
if (object instanceof Throwable)
return ThrowableUtils.getFullStackTrace((Throwable) object);
if (object instanceof Bundle) return bundle2String((Bundle) object);
if (object instanceof Intent) return intent2String((Intent) object);
if (type == JSON) {
return object2Json(object);
} else if (type == XML) {
return formatXml(object.toString());
}
return object.toString();
}
private static String bundle2String(Bundle bundle) {
Iterator<String> iterator = bundle.keySet().iterator();
if (!iterator.hasNext()) {
return "Bundle {}";
}
StringBuilder sb = new StringBuilder(128);
sb.append("Bundle { ");
for (; ; ) {
String key = iterator.next();
Object value = bundle.get(key);
sb.append(key).append('=');
if (value instanceof Bundle) {
sb.append(value == bundle ? "(this Bundle)" : bundle2String((Bundle) value));
} else {
sb.append(formatObject(value));
}
if (!iterator.hasNext()) return sb.append(" }").toString();
sb.append(',').append(' ');
}
}
private static String intent2String(Intent intent) {
StringBuilder sb = new StringBuilder(128);
sb.append("Intent { ");
boolean first = true;
String mAction = intent.getAction();
if (mAction != null) {
sb.append("act=").append(mAction);
first = false;
}
Set<String> mCategories = intent.getCategories();
if (mCategories != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("cat=[");
boolean firstCategory = true;
for (String c : mCategories) {
if (!firstCategory) {
sb.append(',');
}
sb.append(c);
firstCategory = false;
}
sb.append("]");
}
Uri mData = intent.getData();
if (mData != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("dat=").append(mData);
}
String mType = intent.getType();
if (mType != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("typ=").append(mType);
}
int mFlags = intent.getFlags();
if (mFlags != 0) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("flg=0x").append(Integer.toHexString(mFlags));
}
String mPackage = intent.getPackage();
if (mPackage != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("pkg=").append(mPackage);
}
ComponentName mComponent = intent.getComponent();
if (mComponent != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("cmp=").append(mComponent.flattenToShortString());
}
Rect mSourceBounds = intent.getSourceBounds();
if (mSourceBounds != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("bnds=").append(mSourceBounds.toShortString());
}
ClipData mClipData = intent.getClipData();
if (mClipData != null) {
if (!first) {
sb.append(' ');
}
first = false;
clipData2String(mClipData, sb);
}
Bundle mExtras = intent.getExtras();
if (mExtras != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("extras={");
sb.append(bundle2String(mExtras));
sb.append('}');
}
Intent mSelector = intent.getSelector();
if (mSelector != null) {
if (!first) {
sb.append(' ');
}
first = false;
sb.append("sel={");
sb.append(mSelector == intent ? "(this Intent)" : intent2String(mSelector));
sb.append("}");
}
sb.append(" }");
return sb.toString();
}
private static void clipData2String(ClipData clipData, StringBuilder sb) {
ClipData.Item item = clipData.getItemAt(0);
if (item == null) {
sb.append("ClipData.Item {}");
return;
}
sb.append("ClipData.Item { ");
String mHtmlText = item.getHtmlText();
if (mHtmlText != null) {
sb.append("H:");
sb.append(mHtmlText);
sb.append("}");
return;
}
CharSequence mText = item.getText();
if (mText != null) {
sb.append("T:");
sb.append(mText);
sb.append("}");
return;
}
Uri uri = item.getUri();
if (uri != null) {
sb.append("U:").append(uri);
sb.append("}");
return;
}
Intent intent = item.getIntent();
if (intent != null) {
sb.append("I:");
sb.append(intent2String(intent));
sb.append("}");
return;
}
sb.append("NULL");
sb.append("}");
}
private static String object2Json(Object object) {
if (object instanceof CharSequence) {
return JsonUtils.formatJson(object.toString());
}
return object.toString();
}
private static String formatJson(String json) {
try {
for (int i = 0, len = json.length(); i < len; i++) {
char c = json.charAt(i);
if (c == '{') {
return new JSONObject(json).toString(2);
} else if (c == '[') {
return new JSONArray(json).toString(2);
} else if (!Character.isWhitespace(c)) {
return json;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
private static String formatXml(String xml) {
try {
Source xmlInput = new StreamSource(new StringReader(xml));
StreamResult xmlOutput = new StreamResult(new StringWriter());
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
xml = xmlOutput.getWriter().toString().replaceFirst(">", ">" + LINE_SEP);
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
private static String array2String(Object object) {
if (object instanceof Object[]) {
return Arrays.deepToString((Object[]) object);
} else if (object instanceof boolean[]) {
return Arrays.toString((boolean[]) object);
} else if (object instanceof byte[]) {
return Arrays.toString((byte[]) object);
} else if (object instanceof char[]) {
return Arrays.toString((char[]) object);
} else if (object instanceof double[]) {
return Arrays.toString((double[]) object);
} else if (object instanceof float[]) {
return Arrays.toString((float[]) object);
} else if (object instanceof int[]) {
return Arrays.toString((int[]) object);
} else if (object instanceof long[]) {
return Arrays.toString((long[]) object);
} else if (object instanceof short[]) {
return Arrays.toString((short[]) object);
}
throw new IllegalArgumentException("Array has incompatible type: " + object.getClass());
}
}
private static <T> Class getTypeClassFromParadigm(final IFormatter<T> formatter) {
Type[] genericInterfaces = formatter.getClass().getGenericInterfaces();
Type type;
if (genericInterfaces.length == 1) {
type = genericInterfaces[0];
} else {
type = formatter.getClass().getGenericSuperclass();
}
type = ((ParameterizedType) type).getActualTypeArguments()[0];
while (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getRawType();
}
String className = type.toString();
if (className.startsWith("class ")) {
className = className.substring(6);
} else if (className.startsWith("interface ")) {
className = className.substring(10);
}
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
private static Class getClassFromObject(final Object obj) {
Class objClass = obj.getClass();
if (objClass.isAnonymousClass() || objClass.isSynthetic()) {
Type[] genericInterfaces = objClass.getGenericInterfaces();
String className;
if (genericInterfaces.length == 1) {// interface
Type type = genericInterfaces[0];
while (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getRawType();
}
className = type.toString();
} else {// abstract class or lambda
Type type = objClass.getGenericSuperclass();
while (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getRawType();
}
className = type.toString();
}
if (className.startsWith("class ")) {
className = className.substring(6);
} else if (className.startsWith("interface ")) {
className = className.substring(10);
}
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return objClass;
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/MemoryUtils.java
|
package ai.datatower.analytics.utils;
import static android.content.Context.ACTIVITY_SERVICE;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.usage.StorageStatsManager;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.text.TextUtils;
import android.view.Choreographer;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import ai.datatower.analytics.taskqueue.thread.AndroidExecutorKt;
public class MemoryUtils {
static volatile int fps;
static private Boolean shouldListenFps = true;
static volatile int frames = 0;
static volatile Boolean isFpsDoing = false;
static volatile long fpsStartTime = 0;
static final int fpsInterval = 0;
/**
* 获取FPS.
* */
public static int getFPS() {
synchronized (MemoryUtils.class) {
if (fps == 0) {
// 统计不足一秒
return (int) (frames / ((System.nanoTime() - fpsStartTime) / 1000000000.0));
}
return fps;
}
}
public static void toggleShouldListenFps(Boolean shouldListen) {
if (shouldListen == shouldListenFps) return;
shouldListenFps = shouldListen;
if (shouldListenFps) listenFPS(0);
}
synchronized private static void newFrameComes(long frameTime) {
++frames;
final long duration = frameTime - fpsStartTime;
if (duration >= 1000000000L) {
// 本轮统计满 1 秒,计算,重置
double delta = duration / 1000000000.0;
fps = Math.max(1, (int) (frames / delta)); // 最低为 1,屏幕显示的当前帧
frames = 0;
isFpsDoing = false;
}
}
final static private Choreographer.FrameCallback fpsListener = new Choreographer.FrameCallback() {
@Override
public void doFrame(long frameTimeNanos) {
Boolean isDoing;
synchronized (MemoryUtils.class) {
newFrameComes(frameTimeNanos);
isDoing = isFpsDoing;
}
if (isDoing) {
Choreographer.getInstance().postFrameCallback(this);
} else {
// 启动新一轮
listenFPS(fpsInterval);
}
}
};
static final Runnable fpsListenerStarter = new Runnable() {
@Override
public void run() {
if (!shouldListenFps) return;
synchronized (MemoryUtils.class) {
if (!isFpsDoing) {
// 上一轮已结束,才会进行下一轮,确保一个时间段内只会有一轮统计
isFpsDoing = true;
fpsStartTime = System.nanoTime();
Choreographer.getInstance().postFrameCallback(fpsListener);
}
}
}
};
/**
* 监听FPS.
* */
public static void listenFPS(long delayMillis) {
AndroidExecutorKt.runInMain(fpsListenerStarter, delayMillis);
}
private static String getMemoryUsed(Context context) {
StorageBean bean = new StorageBean();
getMemoryInfo(context, bean);
return bean.getUsedMemory() + " / " + bean.getTotalMemory();
}
private static String getStorageUsed(Context context) {
StorageBean bean = new StorageBean();
getStoreInfo(context, bean);
return bean.getUsedStore() + " / " + bean.getTotalStore();
}
/**
* 读取内存信息
*/
public static void getMemoryInfo(Context context, StorageBean bean) {
try {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
manager.getMemoryInfo(info);
long totalMem = info.totalMem;
long availMem = info.availMem;
long usedMem = totalMem - availMem;
String total = readableStorageSize(totalMem);
String usable = readableStorageSize(usedMem);
String free = readableStorageSize(availMem);
bean.setTotalMemory(total);
bean.setFreeMemory(free);
bean.setUsedMemory(usable);
int ratio = (int) ((availMem / (double) totalMem) * 100);
bean.setRatioMemory(ratio);
double v = (double) totalMem / 1024 / 1024 / 1024.0;
String ram;
if (v <= 1) {
ram = "1 GB";
} else if (v <= 2) {
ram = "2 GB";
} else if (v <= 4) {
ram = "4 GB";
} else if (v <= 6) {
ram = "6 GB";
} else if (v <= 8) {
ram = "8 GB";
} else if (v <= 12) {
ram = "12 GB";
} else {
ram = "16 GB";
}
bean.setMemInfo(ram);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取 sd 卡存储信息
*/
public static void getStoreInfo(Context context, StorageBean bean) {
File card = Environment.getExternalStorageDirectory();
bean.setStorePath(card.getAbsolutePath());
long totalSpace = card.getTotalSpace();
long freeSpace = card.getFreeSpace();
long usableSpace = totalSpace - freeSpace;
String total = readableStorageSize(totalSpace);
String usable = readableStorageSize(usableSpace);
String free = readableStorageSize(freeSpace);
bean.setTotalStore(total);
bean.setFreeStore(free);
bean.setUsedStore(usable);
int ratio = (int) ((usableSpace / (double) totalSpace) * 100);
bean.setRatioStore(ratio);
bean.setRomSize(getRealStorage(context));
}
@SuppressLint("DiscouragedPrivateApi")
public static String getRealStorage(Context context) {
long total = 0L;
try {
StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
int version = Build.VERSION.SDK_INT;
float unit = version >= Build.VERSION_CODES.O ? 1000 : 1024;
if (version < Build.VERSION_CODES.M) {
Method getVolumeList = StorageManager.class.getDeclaredMethod("getVolumeList");
StorageVolume[] volumeList = (StorageVolume[]) getVolumeList.invoke(storageManager);
if (volumeList != null) {
Method getPathFile = null;
for (StorageVolume volume : volumeList) {
if (getPathFile == null) {
getPathFile = volume.getClass().getDeclaredMethod("getPathFile");
}
File file = (File) getPathFile.invoke(volume);
total += file.getTotalSpace();
}
}
} else {
@SuppressLint("PrivateApi") Method getVolumes = StorageManager.class.getDeclaredMethod("getVolumes");
List<Object> getVolumeInfo = (List<Object>) getVolumes.invoke(storageManager);
for (Object obj : getVolumeInfo) {
Field getType = obj.getClass().getField("type");
int type = getType.getInt(obj);
if (type == 1) {
long totalSize = 0L;
if (version >= Build.VERSION_CODES.O) {
Method getFsUuid = obj.getClass().getDeclaredMethod("getFsUuid");
String fsUuid = (String) getFsUuid.invoke(obj);
totalSize = getTotalSize(context, fsUuid);
} else if (version >= Build.VERSION_CODES.N_MR1) {
Method getPrimaryStorageSize = StorageManager.class.getMethod("getPrimaryStorageSize");
totalSize = (long) getPrimaryStorageSize.invoke(storageManager);
}
Method isMountedReadable = obj.getClass().getDeclaredMethod("isMountedReadable");
boolean readable = (boolean) isMountedReadable.invoke(obj);
if (readable) {
Method file = obj.getClass().getDeclaredMethod("getPath");
File f = (File) file.invoke(obj);
if (totalSize == 0) {
totalSize = f.getTotalSpace();
}
total += totalSize;
}
} else if (type == 0) {
Method isMountedReadable = obj.getClass().getDeclaredMethod("isMountedReadable");
boolean readable = (boolean) isMountedReadable.invoke(obj);
if (readable) {
Method file = obj.getClass().getDeclaredMethod("getPath");
File f = (File) file.invoke(obj);
total += f.getTotalSpace();
}
}
}
}
return getUnit(total, unit);
} catch (Exception ignore) {
}
return null;
}
private static String[] units = {"B", "KB", "MB", "GB", "TB"};
/**
* 进制转换
*/
private static String getUnit(float size, float base) {
int index = 0;
while (size > base && index < 4) {
size = size / base;
index++;
}
return String.format(Locale.getDefault(), "%.2f %s ", size, units[index]);
}
/**
* API 26 android O
* 获取总共容量大小,包括系统大小
*/
@SuppressLint("NewApi")
private static long getTotalSize(Context context, String fsUuid) {
try {
UUID id;
if (fsUuid == null) {
id = StorageManager.UUID_DEFAULT;
} else {
id = UUID.fromString(fsUuid);
}
StorageStatsManager stats = context.getSystemService(StorageStatsManager.class);
return stats.getTotalBytes(id);
} catch (NoSuchFieldError | NoClassDefFoundError | NullPointerException | IOException e) {
e.printStackTrace();
return -1;
}
}
/**
* 将byte转换为更加友好的单位
*
* @param sizeInB byte
* @return 更加友好的单位(KB、GB等)
*/
public static String readableStorageSize(long sizeInB) {
float floatSize = sizeInB;
int index = 0;
String[] units = new String[]{"B", "KB", "MB", "GB", "TB", "PB"};
while (floatSize > 1000 && index < 5) {
index++;
floatSize /= 1024;
}
String capacityText = new DecimalFormat("###,###,###.##").format(floatSize);
return String.format(Locale.ENGLISH, "%s%s", capacityText, units[index]);
}
/**
* 获取 手机 RAM 信息.
* */
@NonNull
public static String getRAM(Context context) {
try {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
long totalSize = memoryInfo.totalMem;
long availableSize = memoryInfo.availMem;
double total = formatNumber(totalSize / 1024.0 / 1024.0 / 1024.0);
double available = formatNumber(availableSize / 1024.0 / 1024.0 / 1024.0);
return available + "/" + total;
} catch (Exception e) {
e.printStackTrace();
}
return "0";
}
/**
* 判断SD是否挂载.
*/
public boolean isSDCardMount() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
* 通过反射调用获取内置存储和外置sd卡根路径(通用)
* HarmonyOS 正常获取
* ANDROID 11 接口有变动.
*
* @param mContext 上下文
* @param isRemovable 是否可移除,false返回内部存储,true返回外置sd卡
* @return Path
*/
@Nullable
private static String getStoragePath(Context mContext, boolean isRemovable) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
getPath = storageVolumeClazz.getMethod("getPath");
} else {
getPath = storageVolumeClazz.getMethod("getDirectory");
}
Method isRemovableMethod = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = "";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
path = (String) getPath.invoke(storageVolumeElement);
} else {
path = ((File) getPath.invoke(storageVolumeElement)).getAbsolutePath();
}
boolean removable = (Boolean) isRemovableMethod.invoke(storageVolumeElement);
if (isRemovable == removable) {
return path;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String mStoragePath; //保存手机外置卡路径
public static String getDisk(Context context, boolean isExternal) {
try {
if (TextUtils.isEmpty(mStoragePath)) {
mStoragePath = getStoragePath(context, isExternal);
}
if (TextUtils.isEmpty(mStoragePath)) {
return "0";
}
File file = new File(mStoragePath);
if (!file.exists()) {
return "0";
}
StatFs statFs = new StatFs(file.getPath());
long blockCount = statFs.getBlockCountLong();
long blockSize = statFs.getBlockSizeLong();
long totalSpace = blockSize * blockCount;
long availableBlocks = statFs.getAvailableBlocksLong();
long availableSpace = availableBlocks * blockSize;
double total = formatNumber(totalSpace / 1024.0 / 1024.0 / 1024.0);
double available = formatNumber(availableSpace / 1024.0 / 1024.0 / 1024.0);
return available + "/" + total;
} catch (Exception e) {
e.printStackTrace();
}
return "0";
}
/**
* 保留一位小数.
*
* @param num double
* @return 一位小数double
*/
public static double formatNumber(double num) {
return (double) Math.round(num * 10) / 10;
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/NetworkUtil.java
|
package ai.datatower.analytics.utils;
import static android.Manifest.permission.ACCESS_NETWORK_STATE;
import static android.Manifest.permission.INTERNET;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.annotation.RequiresPermission;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import ai.datatower.analytics.taskqueue.MainQueue;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/08/02
* desc : utils about network
* </pre>
*/
public final class NetworkUtil {
private NetworkUtil() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
public enum NetworkType {
NETWORK_ETHERNET,
NETWORK_WIFI,
NETWORK_5G,
NETWORK_4G,
NETWORK_3G,
NETWORK_2G,
NETWORK_UNKNOWN,
NETWORK_NO
}
public static String convertNetworkTypeToString(NetworkType networkType){
if (networkType == NetworkType.NETWORK_ETHERNET) {
return "e";
}
if (networkType == NetworkType.NETWORK_WIFI) {
return "wifi";
}
if (networkType == NetworkType.NETWORK_5G) {
return "5g";
}
if (networkType == NetworkType.NETWORK_4G) {
return "4g";
}
if (networkType == NetworkType.NETWORK_3G) {
return "3g";
}
if (networkType == NetworkType.NETWORK_2G) {
return "2g";
}
if (networkType == NetworkType.NETWORK_UNKNOWN) {
return "unknown_network";
}
if (networkType == NetworkType.NETWORK_NO) {
return "none_network";
}
return "unknown_network";
}
public static String getNetworkTypeString(Application context) {
return convertNetworkTypeToString(getNetworkType(context));
}
/**
* Return type of network.
* <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p>
*
* @return type of network
* <ul>
* <li>{@link NetworkType#NETWORK_ETHERNET} </li>
* <li>{@link NetworkType#NETWORK_WIFI } </li>
* <li>{@link NetworkType#NETWORK_4G } </li>
* <li>{@link NetworkType#NETWORK_3G } </li>
* <li>{@link NetworkType#NETWORK_2G } </li>
* <li>{@link NetworkType#NETWORK_UNKNOWN } </li>
* <li>{@link NetworkType#NETWORK_NO } </li>
* </ul>
*/
@RequiresPermission(ACCESS_NETWORK_STATE)
public static NetworkType getNetworkType(Application context) {
if (isEthernet(context)) {
return NetworkType.NETWORK_ETHERNET;
}
NetworkInfo info = getActiveNetworkInfo(context);
if (info != null && info.isAvailable()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
return NetworkType.NETWORK_WIFI;
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
switch (info.getSubtype()) {
case TelephonyManager.NETWORK_TYPE_GSM:
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return NetworkType.NETWORK_2G;
case TelephonyManager.NETWORK_TYPE_TD_SCDMA:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return NetworkType.NETWORK_3G;
case TelephonyManager.NETWORK_TYPE_IWLAN:
case TelephonyManager.NETWORK_TYPE_LTE:
return NetworkType.NETWORK_4G;
case TelephonyManager.NETWORK_TYPE_NR:
return NetworkType.NETWORK_5G;
default:
String subtypeName = info.getSubtypeName();
if (subtypeName.equalsIgnoreCase("TD-SCDMA")
|| subtypeName.equalsIgnoreCase("WCDMA")
|| subtypeName.equalsIgnoreCase("CDMA2000")) {
return NetworkType.NETWORK_3G;
} else {
return NetworkType.NETWORK_UNKNOWN;
}
}
} else {
return NetworkType.NETWORK_UNKNOWN;
}
}
return NetworkType.NETWORK_NO;
}
/**
* Return whether using ethernet.
* <p>Must hold
* {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p>
*
* @return {@code true}: yes<br>{@code false}: no
*/
@RequiresPermission(ACCESS_NETWORK_STATE)
private static boolean isEthernet(Context context) {
final ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) return false;
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M? isEthernetInternalM(cm) : isEthernetInternal(cm);
}
@RequiresPermission(ACCESS_NETWORK_STATE)
private static boolean isEthernetInternal (@NonNull ConnectivityManager cm) {
final NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
if (info == null) return false;
NetworkInfo.State state = info.getState();
if (null == state) return false;
return state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING;
}
@RequiresPermission(ACCESS_NETWORK_STATE)
@RequiresApi(api = Build.VERSION_CODES.M)
private static boolean isEthernetInternalM(@NonNull ConnectivityManager cm) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities == null) return false;
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET);
}
@RequiresPermission(ACCESS_NETWORK_STATE)
private static NetworkInfo getActiveNetworkInfo(Application context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) return null;
return cm.getActiveNetworkInfo();
}
/**
* Return the ip address.
* <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p>
*
* @param useIPv4 True to use ipv4, false otherwise.
* @return the ip address
*/
@RequiresPermission(INTERNET)
public static String getIPAddress(final boolean useIPv4) {
try {
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
LinkedList<InetAddress> adds = new LinkedList<>();
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
// To prevent phone of xiaomi return "10.0.2.15"
if (!ni.isUp() || ni.isLoopback()) continue;
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
adds.addFirst(addresses.nextElement());
}
}
for (InetAddress add : adds) {
if (!add.isLoopbackAddress()) {
String hostAddress = add.getHostAddress();
boolean isIPv4 = hostAddress.indexOf(':') < 0;
if (useIPv4) {
if (isIPv4) return hostAddress;
} else {
if (!isIPv4) {
int index = hostAddress.indexOf('%');
return index < 0
? hostAddress.toUpperCase(Locale.ENGLISH)
: hostAddress.substring(0, index).toUpperCase(Locale.ENGLISH);
}
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return "";
}
/**
* Return the ip address of broadcast.
*
* @return the ip address of broadcast
*/
public static String getBroadcastIpAddress() {
try {
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
LinkedList<InetAddress> adds = new LinkedList<>();
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
if (!ni.isUp() || ni.isLoopback()) continue;
List<InterfaceAddress> ias = ni.getInterfaceAddresses();
for (int i = 0, size = ias.size(); i < size; i++) {
InterfaceAddress ia = ias.get(i);
InetAddress broadcast = ia.getBroadcast();
if (broadcast != null) {
return broadcast.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return "";
}
/**
* Return the domain address.
* <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p>
*
* @param domain The name of domain.
* @return the domain address
*/
@RequiresPermission(INTERNET)
public static String getDomainAddress(final String domain) {
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(domain);
return inetAddress.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
return "";
}
}
/**
* Register the status of network changed listener.
*
* @param listener The status of network changed listener
*/
@RequiresPermission(ACCESS_NETWORK_STATE)
public static void registerNetworkStatusChangedListener(Application context,final OnNetworkStatusChangedListener listener) {
NetworkChangedReceiver.getInstance(context).registerListener(listener);
}
/**
* Return whether the status of network changed listener has been registered.
*
* @param listener The listener
* @return true to registered, false otherwise.
*/
public static boolean isRegisteredNetworkStatusChangedListener(Application context,final OnNetworkStatusChangedListener listener) {
return NetworkChangedReceiver.getInstance(context).isRegistered(listener);
}
/**
* Unregister the status of network changed listener.
*
* @param listener The status of network changed listener.
*/
public static void unregisterNetworkStatusChangedListener(Application context,final OnNetworkStatusChangedListener listener) {
NetworkChangedReceiver.getInstance(context).unregisterListener(listener);
}
public static final class NetworkChangedReceiver extends BroadcastReceiver {
public NetworkChangedReceiver(Application context) {
mContext = context;
}
private static NetworkChangedReceiver getInstance(Application context) {
mContext = context;
return LazyHolder.INSTANCE;
}
private NetworkType mType;
private final Set<OnNetworkStatusChangedListener> mListeners = new HashSet<>();
private static Application mContext;
@RequiresPermission(ACCESS_NETWORK_STATE)
void registerListener(final OnNetworkStatusChangedListener listener) {
if (listener == null) return;
// ThreadUtils.runOnUiThread(new Runnable() {
// @Override
// @RequiresPermission(ACCESS_NETWORK_STATE)
// public void run() {
// int preSize = mListeners.size();
// mListeners.add(listener);
// if (preSize == 0 && mListeners.size() == 1) {
// mType = getNetworkType(mContext);
// IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
// mContext.registerReceiver(NetworkChangedReceiver.getInstance(mContext), intentFilter);
// }
// }
// });
MainQueue.get().postTask(new Runnable() {
@Override
@RequiresPermission(ACCESS_NETWORK_STATE)
public void run() {
int preSize = mListeners.size();
mListeners.add(listener);
if (preSize == 0 && mListeners.size() == 1) {
mType = getNetworkType(mContext);
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
mContext.registerReceiver(NetworkChangedReceiver.getInstance(mContext), intentFilter);
}
}
});
}
boolean isRegistered(final OnNetworkStatusChangedListener listener) {
if (listener == null) return false;
return mListeners.contains(listener);
}
void unregisterListener(final OnNetworkStatusChangedListener listener) {
if (listener == null) return;
MainQueue.get().postTask(() -> {
int preSize = mListeners.size();
mListeners.remove(listener);
if (preSize == 1 && mListeners.size() == 0) {
mContext.unregisterReceiver(NetworkChangedReceiver.getInstance(mContext));
}
});
}
@Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
MainQueue.get().postTask(() -> {
NetworkType networkType = NetworkUtil.getNetworkType(mContext);
if (mType == networkType) return;
mType = networkType;
if (networkType == NetworkType.NETWORK_NO) {
for (OnNetworkStatusChangedListener listener : mListeners) {
listener.onDisconnected();
}
} else {
for (OnNetworkStatusChangedListener listener : mListeners) {
listener.onConnected(networkType);
}
}
});
// debouncing
// ThreadUtils.runOnUiThreadDelayed(new Runnable() {
// @Override
// @RequiresPermission(ACCESS_NETWORK_STATE)
// public void run() {
// NetworkType networkType = NetworkUtil.getNetworkType(mContext);
// if (mType == networkType) return;
// mType = networkType;
// if (networkType == NetworkType.NETWORK_NO) {
// for (OnNetworkStatusChangedListener listener : mListeners) {
// listener.onDisconnected();
// }
// } else {
// for (OnNetworkStatusChangedListener listener : mListeners) {
// listener.onConnected(networkType);
// }
// }
// }
// }, 1000);
}
}
private static class LazyHolder {
private static final NetworkChangedReceiver INSTANCE = new NetworkChangedReceiver(mContext);
}
}
public interface OnNetworkStatusChangedListener {
void onDisconnected();
void onConnected(NetworkType networkType);
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/ProcessUtil.java
|
package ai.datatower.analytics.utils;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.lang.reflect.Method;
import java.util.List;
/**
*/
public class ProcessUtil {
private static String currentProcessName;
/**
* @return 当前进程名
*/
@Nullable
public static String getCurrentProcessName(@NonNull Context context) {
if (!TextUtils.isEmpty(currentProcessName)) {
return currentProcessName;
}
//1)通过Application的API获取当前进程名
currentProcessName = getCurrentProcessNameByApplication();
if (!TextUtils.isEmpty(currentProcessName)) {
return currentProcessName;
}
//2)通过反射ActivityThread获取当前进程名
currentProcessName = getCurrentProcessNameByActivityThread();
if (!TextUtils.isEmpty(currentProcessName)) {
return currentProcessName;
}
//3)通过ActivityManager获取当前进程名
currentProcessName = getCurrentProcessNameByActivityManager(context);
return currentProcessName;
}
/**
* 通过Application新的API获取进程名,无需反射,无需IPC,效率最高。
*/
public static String getCurrentProcessNameByApplication() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
return Application.getProcessName();
}
return null;
}
/**
* 通过反射ActivityThread获取进程名,避免了ipc
*/
public static String getCurrentProcessNameByActivityThread() {
String processName = null;
try {
final Method declaredMethod = Class.forName("android.app.ActivityThread", false, Application.class.getClassLoader())
.getDeclaredMethod("currentProcessName", (Class<?>[]) new Class[0]);
declaredMethod.setAccessible(true);
final Object invoke = declaredMethod.invoke(null, new Object[0]);
if (invoke instanceof String) {
processName = (String) invoke;
}
} catch (Throwable e) {
e.printStackTrace();
}
return processName;
}
/**
* 通过ActivityManager 获取进程名,需要IPC通信
*/
public static String getCurrentProcessNameByActivityManager(@NonNull Context context) {
if (context == null) {
return null;
}
int pid = android.os.Process.myPid();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (am != null) {
List<ActivityManager.RunningAppProcessInfo> runningAppList = am.getRunningAppProcesses();
if (runningAppList != null) {
for (ActivityManager.RunningAppProcessInfo processInfo : runningAppList) {
if (processInfo.pid == pid) {
return processInfo.processName;
}
}
}
}
return null;
}
public static boolean isMainProcess(Context context) {
//获取当前进程名,并与主进程对比,来判断是否为主进程
String processName = ProcessUtil.getCurrentProcessName(context);
return context.getPackageName().equals(processName);
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/StorageBean.java
|
package ai.datatower.analytics.utils;
import androidx.annotation.NonNull;
/**
* Created by chensongsong on 2020/6/1.
*/
public class StorageBean {
/**
* 剩余存储空间
*/
private String freeStore;
/**
* 已用存储空间
*/
private String usedStore;
/**
* 总共存储空间
*/
private String totalStore;
/**
* 使用率
*/
private int ratioStore;
/**
* 存储路径
*/
private String storePath;
/**
* 剩余存储空间
*/
private String freeMemory;
/**
* 已用存储空间
*/
private String usedMemory;
/**
* 总共存储空间
*/
private String totalMemory;
/**
* 使用率
*/
private int ratioMemory;
/**
* 内存信息
*/
private String memInfo;
/**
* 真实 ROM 空间
*/
private String romSize;
public String getFreeStore() {
return freeStore;
}
public void setFreeStore(String freeStore) {
this.freeStore = freeStore;
}
public String getUsedStore() {
return usedStore;
}
public void setUsedStore(String usedStore) {
this.usedStore = usedStore;
}
public String getTotalStore() {
return totalStore;
}
public void setTotalStore(String totalStore) {
this.totalStore = totalStore;
}
public int getRatioStore() {
return ratioStore;
}
public void setRatioStore(int ratioStore) {
this.ratioStore = ratioStore;
}
public String getStorePath() {
return storePath;
}
public void setStorePath(String storePath) {
this.storePath = storePath;
}
public String getFreeMemory() {
return freeMemory;
}
public void setFreeMemory(String freeMemory) {
this.freeMemory = freeMemory;
}
public String getUsedMemory() {
return usedMemory;
}
public void setUsedMemory(String usedMemory) {
this.usedMemory = usedMemory;
}
public String getTotalMemory() {
return totalMemory;
}
public void setTotalMemory(String totalMemory) {
this.totalMemory = totalMemory;
}
public int getRatioMemory() {
return ratioMemory;
}
public void setRatioMemory(int ratioMemory) {
this.ratioMemory = ratioMemory;
}
public String getMemInfo() {
return memInfo;
}
public void setMemInfo(String memInfo) {
this.memInfo = memInfo;
}
public String getRomSize() {
return romSize;
}
public void setRomSize(String romSize) {
this.romSize = romSize;
}
@NonNull
@Override
public String toString() {
return "StorageBean{" +
"freeStore='" + freeStore + '\'' +
", usedStore='" + usedStore + '\'' +
", totalStore='" + totalStore + '\'' +
", ratioStore=" + ratioStore +
", storePath='" + storePath + '\'' +
", freeMemory='" + freeMemory + '\'' +
", usedMemory='" + usedMemory + '\'' +
", totalMemory='" + totalMemory + '\'' +
", ratioMemory=" + ratioMemory +
", memInfo='" + memInfo + '\'' +
", romSize='" + romSize + '\'' +
'}';
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/ThreadUtils.java
|
package ai.datatower.analytics.utils;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.CallSuper;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/05/08
* desc : utils about thread
* </pre>
*/
public final class ThreadUtils {
private static final Handler HANDLER = new Handler(Looper.getMainLooper());
private static final Map<Integer, Map<Integer, ExecutorService>> TYPE_PRIORITY_POOLS = new HashMap<>();
private static final Map<Task, ExecutorService> TASK_POOL_MAP = new ConcurrentHashMap<>();
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final Timer TIMER = new Timer();
private static final byte TYPE_SINGLE = -1;
private static final byte TYPE_CACHED = -2;
private static final byte TYPE_IO = -4;
private static final byte TYPE_CPU = -8;
private static Executor sDeliver;
/**
* Return whether the thread is the main thread.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isMainThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
public static Handler getMainHandler() {
return HANDLER;
}
public static void runOnUiThread(final Runnable runnable) {
if (Looper.myLooper() == Looper.getMainLooper()) {
runnable.run();
} else {
HANDLER.post(runnable);
}
}
public static void runOnUiThreadDelayed(final Runnable runnable, long delayMillis) {
HANDLER.postDelayed(runnable, delayMillis);
}
/**
* Return a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue, using the provided
* ThreadFactory to create new threads when needed.
*
* @param size The size of thread in the pool.
* @return a fixed thread pool
*/
public static ExecutorService getFixedPool(@IntRange(from = 1) final int size) {
return getPoolByTypeAndPriority(size);
}
/**
* Return a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue, using the provided
* ThreadFactory to create new threads when needed.
*
* @param size The size of thread in the pool.
* @param priority The priority of thread in the poll.
* @return a fixed thread pool
*/
public static ExecutorService getFixedPool(@IntRange(from = 1) final int size,
@IntRange(from = 1, to = 10) final int priority) {
return getPoolByTypeAndPriority(size, priority);
}
/**
* Return a thread pool that uses a single worker thread operating
* off an unbounded queue, and uses the provided ThreadFactory to
* create a new thread when needed.
*
* @return a single thread pool
*/
public static ExecutorService getSinglePool() {
return getPoolByTypeAndPriority(TYPE_SINGLE);
}
/**
* Return a thread pool that uses a single worker thread operating
* off an unbounded queue, and uses the provided ThreadFactory to
* create a new thread when needed.
*
* @param priority The priority of thread in the poll.
* @return a single thread pool
*/
public static ExecutorService getSinglePool(@IntRange(from = 1, to = 10) final int priority) {
return getPoolByTypeAndPriority(TYPE_SINGLE, priority);
}
/**
* Return a thread pool that creates new threads as needed, but
* will reuse previously constructed threads when they are
* available.
*
* @return a cached thread pool
*/
public static ExecutorService getCachedPool() {
return getPoolByTypeAndPriority(TYPE_CACHED);
}
/**
* Return a thread pool that creates new threads as needed, but
* will reuse previously constructed threads when they are
* available.
*
* @param priority The priority of thread in the poll.
* @return a cached thread pool
*/
public static ExecutorService getCachedPool(@IntRange(from = 1, to = 10) final int priority) {
return getPoolByTypeAndPriority(TYPE_CACHED, priority);
}
/**
* Return a thread pool that creates (2 * CPU_COUNT + 1) threads
* operating off a queue which size is 128.
*
* @return a IO thread pool
*/
public static ExecutorService getIoPool() {
return getPoolByTypeAndPriority(TYPE_IO);
}
/**
* Return a thread pool that creates (2 * CPU_COUNT + 1) threads
* operating off a queue which size is 128.
*
* @param priority The priority of thread in the poll.
* @return a IO thread pool
*/
public static ExecutorService getIoPool(@IntRange(from = 1, to = 10) final int priority) {
return getPoolByTypeAndPriority(TYPE_IO, priority);
}
/**
* Return a thread pool that creates (CPU_COUNT + 1) threads
* operating off a queue which size is 128 and the maximum
* number of threads equals (2 * CPU_COUNT + 1).
*
* @return a cpu thread pool for
*/
public static ExecutorService getCpuPool() {
return getPoolByTypeAndPriority(TYPE_CPU);
}
/**
* Return a thread pool that creates (CPU_COUNT + 1) threads
* operating off a queue which size is 128 and the maximum
* number of threads equals (2 * CPU_COUNT + 1).
*
* @param priority The priority of thread in the poll.
* @return a cpu thread pool for
*/
public static ExecutorService getCpuPool(@IntRange(from = 1, to = 10) final int priority) {
return getPoolByTypeAndPriority(TYPE_CPU, priority);
}
/**
* Executes the given task in a fixed thread pool.
*
* @param size The size of thread in the fixed thread pool.
* @param task The task to execute.
* @param <T> The type of the task's result.
*/
public static <T> void executeByFixed(@IntRange(from = 1) final int size, final Task<T> task) {
execute(getPoolByTypeAndPriority(size), task);
}
/**
* Executes the given task in a fixed thread pool.
*
* @param size The size of thread in the fixed thread pool.
* @param task The task to execute.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByFixed(@IntRange(from = 1) final int size,
final Task<T> task,
@IntRange(from = 1, to = 10) final int priority) {
execute(getPoolByTypeAndPriority(size, priority), task);
}
/**
* Executes the given task in a fixed thread pool after the given delay.
*
* @param size The size of thread in the fixed thread pool.
* @param task The task to execute.
* @param delay The time from now to delay execution.
* @param unit The time unit of the delay parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeByFixedWithDelay(@IntRange(from = 1) final int size,
final Task<T> task,
final long delay,
final TimeUnit unit) {
executeWithDelay(getPoolByTypeAndPriority(size), task, delay, unit);
}
/**
* Executes the given task in a fixed thread pool after the given delay.
*
* @param size The size of thread in the fixed thread pool.
* @param task The task to execute.
* @param delay The time from now to delay execution.
* @param unit The time unit of the delay parameter.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByFixedWithDelay(@IntRange(from = 1) final int size,
final Task<T> task,
final long delay,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeWithDelay(getPoolByTypeAndPriority(size, priority), task, delay, unit);
}
/**
* Executes the given task in a fixed thread pool at fix rate.
*
* @param size The size of thread in the fixed thread pool.
* @param task The task to execute.
* @param period The period between successive executions.
* @param unit The time unit of the period parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeByFixedAtFixRate(@IntRange(from = 1) final int size,
final Task<T> task,
final long period,
final TimeUnit unit) {
executeAtFixedRate(getPoolByTypeAndPriority(size), task, 0, period, unit);
}
/**
* Executes the given task in a fixed thread pool at fix rate.
*
* @param size The size of thread in the fixed thread pool.
* @param task The task to execute.
* @param period The period between successive executions.
* @param unit The time unit of the period parameter.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByFixedAtFixRate(@IntRange(from = 1) final int size,
final Task<T> task,
final long period,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeAtFixedRate(getPoolByTypeAndPriority(size, priority), task, 0, period, unit);
}
/**
* Executes the given task in a fixed thread pool at fix rate.
*
* @param size The size of thread in the fixed thread pool.
* @param task The task to execute.
* @param initialDelay The time to delay first execution.
* @param period The period between successive executions.
* @param unit The time unit of the initialDelay and period parameters.
* @param <T> The type of the task's result.
*/
public static <T> void executeByFixedAtFixRate(@IntRange(from = 1) final int size,
final Task<T> task,
long initialDelay,
final long period,
final TimeUnit unit) {
executeAtFixedRate(getPoolByTypeAndPriority(size), task, initialDelay, period, unit);
}
/**
* Executes the given task in a fixed thread pool at fix rate.
*
* @param size The size of thread in the fixed thread pool.
* @param task The task to execute.
* @param initialDelay The time to delay first execution.
* @param period The period between successive executions.
* @param unit The time unit of the initialDelay and period parameters.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByFixedAtFixRate(@IntRange(from = 1) final int size,
final Task<T> task,
long initialDelay,
final long period,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeAtFixedRate(getPoolByTypeAndPriority(size, priority), task, initialDelay, period, unit);
}
/**
* Executes the given task in a single thread pool.
*
* @param task The task to execute.
* @param <T> The type of the task's result.
*/
public static <T> void executeBySingle(final Task<T> task) {
execute(getPoolByTypeAndPriority(TYPE_SINGLE), task);
}
/**
* Executes the given task in a single thread pool.
*
* @param task The task to execute.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeBySingle(final Task<T> task,
@IntRange(from = 1, to = 10) final int priority) {
execute(getPoolByTypeAndPriority(TYPE_SINGLE, priority), task);
}
/**
* Executes the given task in a single thread pool after the given delay.
*
* @param task The task to execute.
* @param delay The time from now to delay execution.
* @param unit The time unit of the delay parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeBySingleWithDelay(final Task<T> task,
final long delay,
final TimeUnit unit) {
executeWithDelay(getPoolByTypeAndPriority(TYPE_SINGLE), task, delay, unit);
}
/**
* Executes the given task in a single thread pool after the given delay.
*
* @param task The task to execute.
* @param delay The time from now to delay execution.
* @param unit The time unit of the delay parameter.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeBySingleWithDelay(final Task<T> task,
final long delay,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeWithDelay(getPoolByTypeAndPriority(TYPE_SINGLE, priority), task, delay, unit);
}
/**
* Executes the given task in a single thread pool at fix rate.
*
* @param task The task to execute.
* @param period The period between successive executions.
* @param unit The time unit of the period parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeBySingleAtFixRate(final Task<T> task,
final long period,
final TimeUnit unit) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_SINGLE), task, 0, period, unit);
}
/**
* Executes the given task in a single thread pool at fix rate.
*
* @param task The task to execute.
* @param period The period between successive executions.
* @param unit The time unit of the period parameter.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeBySingleAtFixRate(final Task<T> task,
final long period,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_SINGLE, priority), task, 0, period, unit);
}
/**
* Executes the given task in a single thread pool at fix rate.
*
* @param task The task to execute.
* @param initialDelay The time to delay first execution.
* @param period The period between successive executions.
* @param unit The time unit of the initialDelay and period parameters.
* @param <T> The type of the task's result.
*/
public static <T> void executeBySingleAtFixRate(final Task<T> task,
long initialDelay,
final long period,
final TimeUnit unit) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_SINGLE), task, initialDelay, period, unit);
}
/**
* Executes the given task in a single thread pool at fix rate.
*
* @param task The task to execute.
* @param initialDelay The time to delay first execution.
* @param period The period between successive executions.
* @param unit The time unit of the initialDelay and period parameters.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeBySingleAtFixRate(final Task<T> task,
long initialDelay,
final long period,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeAtFixedRate(
getPoolByTypeAndPriority(TYPE_SINGLE, priority), task, initialDelay, period, unit
);
}
/**
* Executes the given task in a cached thread pool.
*
* @param task The task to execute.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCached(final Task<T> task) {
execute(getPoolByTypeAndPriority(TYPE_CACHED), task);
}
/**
* Executes the given task in a cached thread pool.
*
* @param task The task to execute.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCached(final Task<T> task,
@IntRange(from = 1, to = 10) final int priority) {
execute(getPoolByTypeAndPriority(TYPE_CACHED, priority), task);
}
/**
* Executes the given task in a cached thread pool after the given delay.
*
* @param task The task to execute.
* @param delay The time from now to delay execution.
* @param unit The time unit of the delay parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCachedWithDelay(final Task<T> task,
final long delay,
final TimeUnit unit) {
executeWithDelay(getPoolByTypeAndPriority(TYPE_CACHED), task, delay, unit);
}
/**
* Executes the given task in a cached thread pool after the given delay.
*
* @param task The task to execute.
* @param delay The time from now to delay execution.
* @param unit The time unit of the delay parameter.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCachedWithDelay(final Task<T> task,
final long delay,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeWithDelay(getPoolByTypeAndPriority(TYPE_CACHED, priority), task, delay, unit);
}
/**
* Executes the given task in a cached thread pool at fix rate.
*
* @param task The task to execute.
* @param period The period between successive executions.
* @param unit The time unit of the period parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCachedAtFixRate(final Task<T> task,
final long period,
final TimeUnit unit) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_CACHED), task, 0, period, unit);
}
/**
* Executes the given task in a cached thread pool at fix rate.
*
* @param task The task to execute.
* @param period The period between successive executions.
* @param unit The time unit of the period parameter.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCachedAtFixRate(final Task<T> task,
final long period,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_CACHED, priority), task, 0, period, unit);
}
/**
* Executes the given task in a cached thread pool at fix rate.
*
* @param task The task to execute.
* @param initialDelay The time to delay first execution.
* @param period The period between successive executions.
* @param unit The time unit of the initialDelay and period parameters.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCachedAtFixRate(final Task<T> task,
long initialDelay,
final long period,
final TimeUnit unit) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_CACHED), task, initialDelay, period, unit);
}
/**
* Executes the given task in a cached thread pool at fix rate.
*
* @param task The task to execute.
* @param initialDelay The time to delay first execution.
* @param period The period between successive executions.
* @param unit The time unit of the initialDelay and period parameters.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCachedAtFixRate(final Task<T> task,
long initialDelay,
final long period,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeAtFixedRate(
getPoolByTypeAndPriority(TYPE_CACHED, priority), task, initialDelay, period, unit
);
}
/**
* Executes the given task in an IO thread pool.
*
* @param task The task to execute.
* @param <T> The type of the task's result.
*/
public static <T> void executeByIo(final Task<T> task) {
execute(getPoolByTypeAndPriority(TYPE_IO), task);
}
/**
* Executes the given task in an IO thread pool.
*
* @param task The task to execute.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByIo(final Task<T> task,
@IntRange(from = 1, to = 10) final int priority) {
execute(getPoolByTypeAndPriority(TYPE_IO, priority), task);
}
/**
* Executes the given task in an IO thread pool after the given delay.
*
* @param task The task to execute.
* @param delay The time from now to delay execution.
* @param unit The time unit of the delay parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeByIoWithDelay(final Task<T> task,
final long delay,
final TimeUnit unit) {
executeWithDelay(getPoolByTypeAndPriority(TYPE_IO), task, delay, unit);
}
/**
* Executes the given task in an IO thread pool after the given delay.
*
* @param task The task to execute.
* @param delay The time from now to delay execution.
* @param unit The time unit of the delay parameter.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByIoWithDelay(final Task<T> task,
final long delay,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeWithDelay(getPoolByTypeAndPriority(TYPE_IO, priority), task, delay, unit);
}
/**
* Executes the given task in an IO thread pool at fix rate.
*
* @param task The task to execute.
* @param period The period between successive executions.
* @param unit The time unit of the period parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeByIoAtFixRate(final Task<T> task,
final long period,
final TimeUnit unit) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_IO), task, 0, period, unit);
}
/**
* Executes the given task in an IO thread pool at fix rate.
*
* @param task The task to execute.
* @param period The period between successive executions.
* @param unit The time unit of the period parameter.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByIoAtFixRate(final Task<T> task,
final long period,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_IO, priority), task, 0, period, unit);
}
/**
* Executes the given task in an IO thread pool at fix rate.
*
* @param task The task to execute.
* @param initialDelay The time to delay first execution.
* @param period The period between successive executions.
* @param unit The time unit of the initialDelay and period parameters.
* @param <T> The type of the task's result.
*/
public static <T> void executeByIoAtFixRate(final Task<T> task,
long initialDelay,
final long period,
final TimeUnit unit) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_IO), task, initialDelay, period, unit);
}
/**
* Executes the given task in an IO thread pool at fix rate.
*
* @param task The task to execute.
* @param initialDelay The time to delay first execution.
* @param period The period between successive executions.
* @param unit The time unit of the initialDelay and period parameters.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByIoAtFixRate(final Task<T> task,
long initialDelay,
final long period,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeAtFixedRate(
getPoolByTypeAndPriority(TYPE_IO, priority), task, initialDelay, period, unit
);
}
/**
* Executes the given task in a cpu thread pool.
*
* @param task The task to execute.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCpu(final Task<T> task) {
execute(getPoolByTypeAndPriority(TYPE_CPU), task);
}
/**
* Executes the given task in a cpu thread pool.
*
* @param task The task to execute.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCpu(final Task<T> task,
@IntRange(from = 1, to = 10) final int priority) {
execute(getPoolByTypeAndPriority(TYPE_CPU, priority), task);
}
/**
* Executes the given task in a cpu thread pool after the given delay.
*
* @param task The task to execute.
* @param delay The time from now to delay execution.
* @param unit The time unit of the delay parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCpuWithDelay(final Task<T> task,
final long delay,
final TimeUnit unit) {
executeWithDelay(getPoolByTypeAndPriority(TYPE_CPU), task, delay, unit);
}
/**
* Executes the given task in a cpu thread pool after the given delay.
*
* @param task The task to execute.
* @param delay The time from now to delay execution.
* @param unit The time unit of the delay parameter.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCpuWithDelay(final Task<T> task,
final long delay,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeWithDelay(getPoolByTypeAndPriority(TYPE_CPU, priority), task, delay, unit);
}
/**
* Executes the given task in a cpu thread pool at fix rate.
*
* @param task The task to execute.
* @param period The period between successive executions.
* @param unit The time unit of the period parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCpuAtFixRate(final Task<T> task,
final long period,
final TimeUnit unit) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_CPU), task, 0, period, unit);
}
/**
* Executes the given task in a cpu thread pool at fix rate.
*
* @param task The task to execute.
* @param period The period between successive executions.
* @param unit The time unit of the period parameter.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCpuAtFixRate(final Task<T> task,
final long period,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_CPU, priority), task, 0, period, unit);
}
/**
* Executes the given task in a cpu thread pool at fix rate.
*
* @param task The task to execute.
* @param initialDelay The time to delay first execution.
* @param period The period between successive executions.
* @param unit The time unit of the initialDelay and period parameters.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCpuAtFixRate(final Task<T> task,
long initialDelay,
final long period,
final TimeUnit unit) {
executeAtFixedRate(getPoolByTypeAndPriority(TYPE_CPU), task, initialDelay, period, unit);
}
/**
* Executes the given task in a cpu thread pool at fix rate.
*
* @param task The task to execute.
* @param initialDelay The time to delay first execution.
* @param period The period between successive executions.
* @param unit The time unit of the initialDelay and period parameters.
* @param priority The priority of thread in the poll.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCpuAtFixRate(final Task<T> task,
long initialDelay,
final long period,
final TimeUnit unit,
@IntRange(from = 1, to = 10) final int priority) {
executeAtFixedRate(
getPoolByTypeAndPriority(TYPE_CPU, priority), task, initialDelay, period, unit
);
}
/**
* Executes the given task in a custom thread pool.
*
* @param pool The custom thread pool.
* @param task The task to execute.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCustom(final ExecutorService pool, final Task<T> task) {
execute(pool, task);
}
/**
* Executes the given task in a custom thread pool after the given delay.
*
* @param pool The custom thread pool.
* @param task The task to execute.
* @param delay The time from now to delay execution.
* @param unit The time unit of the delay parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCustomWithDelay(final ExecutorService pool,
final Task<T> task,
final long delay,
final TimeUnit unit) {
executeWithDelay(pool, task, delay, unit);
}
/**
* Executes the given task in a custom thread pool at fix rate.
*
* @param pool The custom thread pool.
* @param task The task to execute.
* @param period The period between successive executions.
* @param unit The time unit of the period parameter.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCustomAtFixRate(final ExecutorService pool,
final Task<T> task,
final long period,
final TimeUnit unit) {
executeAtFixedRate(pool, task, 0, period, unit);
}
/**
* Executes the given task in a custom thread pool at fix rate.
*
* @param pool The custom thread pool.
* @param task The task to execute.
* @param initialDelay The time to delay first execution.
* @param period The period between successive executions.
* @param unit The time unit of the initialDelay and period parameters.
* @param <T> The type of the task's result.
*/
public static <T> void executeByCustomAtFixRate(final ExecutorService pool,
final Task<T> task,
long initialDelay,
final long period,
final TimeUnit unit) {
executeAtFixedRate(pool, task, initialDelay, period, unit);
}
/**
* Cancel the given task.
*
* @param task The task to cancel.
*/
public static void cancel(final Task task) {
if (task == null) return;
task.cancel();
}
/**
* Cancel the given tasks.
*
* @param tasks The tasks to cancel.
*/
public static void cancel(final Task... tasks) {
if (tasks == null || tasks.length == 0) return;
for (Task task : tasks) {
if (task == null) continue;
task.cancel();
}
}
/**
* Cancel the given tasks.
*
* @param tasks The tasks to cancel.
*/
public static void cancel(final List<Task> tasks) {
if (tasks == null || tasks.size() == 0) return;
for (Task task : tasks) {
if (task == null) continue;
task.cancel();
}
}
/**
* Cancel the tasks in pool.
*
* @param executorService The pool.
*/
public static void cancel(ExecutorService executorService) {
if (executorService instanceof ThreadPoolExecutor4Util) {
for (Map.Entry<Task, ExecutorService> taskTaskInfoEntry : TASK_POOL_MAP.entrySet()) {
if (taskTaskInfoEntry.getValue() == executorService) {
cancel(taskTaskInfoEntry.getKey());
}
}
} else {
Log.e("ThreadUtils", "The executorService is not ThreadUtils's pool.");
}
}
/**
* Set the deliver.
*
* @param deliver The deliver.
*/
public static void setDeliver(final Executor deliver) {
sDeliver = deliver;
}
private static <T> void execute(final ExecutorService pool, final Task<T> task) {
execute(pool, task, 0, 0, null);
}
private static <T> void executeWithDelay(final ExecutorService pool,
final Task<T> task,
final long delay,
final TimeUnit unit) {
execute(pool, task, delay, 0, unit);
}
private static <T> void executeAtFixedRate(final ExecutorService pool,
final Task<T> task,
long delay,
final long period,
final TimeUnit unit) {
execute(pool, task, delay, period, unit);
}
private static <T> void execute(final ExecutorService pool, final Task<T> task,
long delay, final long period, final TimeUnit unit) {
synchronized (TASK_POOL_MAP) {
if (TASK_POOL_MAP.get(task) != null) {
Log.e("ThreadUtils", "Task can only be executed once.");
return;
}
TASK_POOL_MAP.put(task, pool);
}
if (period == 0) {
if (delay == 0) {
pool.execute(task);
} else {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
pool.execute(task);
}
};
TIMER.schedule(timerTask, unit.toMillis(delay));
}
} else {
task.setSchedule(true);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
pool.execute(task);
}
};
TIMER.scheduleAtFixedRate(timerTask, unit.toMillis(delay), unit.toMillis(period));
}
}
private static ExecutorService getPoolByTypeAndPriority(final int type) {
return getPoolByTypeAndPriority(type, Thread.NORM_PRIORITY);
}
private static ExecutorService getPoolByTypeAndPriority(final int type, final int priority) {
synchronized (TYPE_PRIORITY_POOLS) {
ExecutorService pool;
Map<Integer, ExecutorService> priorityPools = TYPE_PRIORITY_POOLS.get(type);
if (priorityPools == null) {
priorityPools = new ConcurrentHashMap<>();
pool = ThreadPoolExecutor4Util.createPool(type, priority);
priorityPools.put(priority, pool);
TYPE_PRIORITY_POOLS.put(type, priorityPools);
} else {
pool = priorityPools.get(priority);
if (pool == null) {
pool = ThreadPoolExecutor4Util.createPool(type, priority);
priorityPools.put(priority, pool);
}
}
return pool;
}
}
static final class ThreadPoolExecutor4Util extends ThreadPoolExecutor {
private static ExecutorService createPool(final int type, final int priority) {
switch (type) {
case TYPE_SINGLE:
return new ThreadPoolExecutor4Util(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue4Util(),
new UtilsThreadFactory("single", priority)
);
case TYPE_CACHED:
return new ThreadPoolExecutor4Util(0, 128,
60L, TimeUnit.SECONDS,
new LinkedBlockingQueue4Util(true),
new UtilsThreadFactory("cached", priority)
);
case TYPE_IO:
return new ThreadPoolExecutor4Util(2 * CPU_COUNT + 1, 2 * CPU_COUNT + 1,
30, TimeUnit.SECONDS,
new LinkedBlockingQueue4Util(),
new UtilsThreadFactory("io", priority)
);
case TYPE_CPU:
return new ThreadPoolExecutor4Util(CPU_COUNT + 1, 2 * CPU_COUNT + 1,
30, TimeUnit.SECONDS,
new LinkedBlockingQueue4Util(true),
new UtilsThreadFactory("cpu", priority)
);
default:
return new ThreadPoolExecutor4Util(type, type,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue4Util(),
new UtilsThreadFactory("fixed(" + type + ")", priority)
);
}
}
private final AtomicInteger mSubmittedCount = new AtomicInteger();
private LinkedBlockingQueue4Util mWorkQueue;
ThreadPoolExecutor4Util(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
LinkedBlockingQueue4Util workQueue,
ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize,
keepAliveTime, unit,
workQueue,
threadFactory
);
workQueue.mPool = this;
mWorkQueue = workQueue;
}
private int getSubmittedCount() {
return mSubmittedCount.get();
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
mSubmittedCount.decrementAndGet();
super.afterExecute(r, t);
}
@Override
public void execute(@NonNull Runnable command) {
if (this.isShutdown()) return;
mSubmittedCount.incrementAndGet();
try {
super.execute(command);
} catch (RejectedExecutionException ignore) {
Log.e("ThreadUtils", "This will not happen!");
mWorkQueue.offer(command);
} catch (Throwable t) {
mSubmittedCount.decrementAndGet();
}
}
}
private static final class LinkedBlockingQueue4Util extends LinkedBlockingQueue<Runnable> {
private volatile ThreadPoolExecutor4Util mPool;
private int mCapacity = Integer.MAX_VALUE;
LinkedBlockingQueue4Util() {
super();
}
LinkedBlockingQueue4Util(boolean isAddSubThreadFirstThenAddQueue) {
super();
if (isAddSubThreadFirstThenAddQueue) {
mCapacity = 0;
}
}
LinkedBlockingQueue4Util(int capacity) {
super();
mCapacity = capacity;
}
@Override
public boolean offer(@NonNull Runnable runnable) {
if (mCapacity <= size() &&
mPool != null && mPool.getPoolSize() < mPool.getMaximumPoolSize()) {
// create a non-core thread
return false;
}
return super.offer(runnable);
}
}
static final class UtilsThreadFactory extends AtomicLong
implements ThreadFactory {
private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
private static final long serialVersionUID = -9209200509960368598L;
private final String namePrefix;
private final int priority;
private final boolean isDaemon;
UtilsThreadFactory(String prefix, int priority) {
this(prefix, priority, false);
}
UtilsThreadFactory(String prefix, int priority, boolean isDaemon) {
namePrefix = prefix + "-pool-" +
POOL_NUMBER.getAndIncrement() +
"-thread-";
this.priority = priority;
this.isDaemon = isDaemon;
}
@Override
public Thread newThread(@NonNull Runnable r) {
Thread t = new Thread(r, namePrefix + getAndIncrement()) {
@Override
public void run() {
try {
super.run();
} catch (Throwable t) {
Log.e("ThreadUtils", "Request threw uncaught throwable", t);
}
}
};
t.setDaemon(isDaemon);
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
e.printStackTrace();
}
});
t.setPriority(priority);
return t;
}
}
public abstract static class SimpleTask<T> extends Task<T> {
@Override
public void onCancel() {
Log.e("ThreadUtils", "onCancel: " + Thread.currentThread());
}
@Override
public void onFail(Throwable t) {
Log.e("ThreadUtils", "onFail: ", t);
}
}
public abstract static class Task<T> implements Runnable {
private static final int NEW = 0;
private static final int RUNNING = 1;
private static final int EXCEPTIONAL = 2;
private static final int COMPLETING = 3;
private static final int CANCELLED = 4;
private static final int INTERRUPTED = 5;
private static final int TIMEOUT = 6;
private final AtomicInteger state = new AtomicInteger(NEW);
private volatile boolean isSchedule;
private volatile Thread runner;
private Timer mTimer;
private long mTimeoutMillis;
private OnTimeoutListener mTimeoutListener;
private Executor deliver;
public abstract T doInBackground() throws Throwable;
public abstract void onSuccess(T result);
public abstract void onCancel();
public abstract void onFail(Throwable t);
@Override
public void run() {
if (isSchedule) {
if (runner == null) {
if (!state.compareAndSet(NEW, RUNNING)) return;
runner = Thread.currentThread();
if (mTimeoutListener != null) {
Log.w("ThreadUtils", "Scheduled task doesn't support timeout.");
}
} else {
if (state.get() != RUNNING) return;
}
} else {
if (!state.compareAndSet(NEW, RUNNING)) return;
runner = Thread.currentThread();
if (mTimeoutListener != null) {
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
if (!isDone() && mTimeoutListener != null) {
timeout();
mTimeoutListener.onTimeout();
}
}
}, mTimeoutMillis);
}
}
try {
final T result = doInBackground();
if (isSchedule) {
if (state.get() != RUNNING) return;
getDeliver().execute(new Runnable() {
@Override
public void run() {
onSuccess(result);
}
});
} else {
if (!state.compareAndSet(RUNNING, COMPLETING)) return;
getDeliver().execute(new Runnable() {
@Override
public void run() {
onSuccess(result);
onDone();
}
});
}
} catch (InterruptedException ignore) {
state.compareAndSet(CANCELLED, INTERRUPTED);
} catch (final Throwable throwable) {
if (!state.compareAndSet(RUNNING, EXCEPTIONAL)) return;
getDeliver().execute(new Runnable() {
@Override
public void run() {
onFail(throwable);
onDone();
}
});
}
}
public void cancel() {
cancel(true);
}
public void cancel(boolean mayInterruptIfRunning) {
synchronized (state) {
if (state.get() > RUNNING) return;
state.set(CANCELLED);
}
if (mayInterruptIfRunning) {
if (runner != null) {
runner.interrupt();
}
}
getDeliver().execute(new Runnable() {
@Override
public void run() {
onCancel();
onDone();
}
});
}
private void timeout() {
synchronized (state) {
if (state.get() > RUNNING) return;
state.set(TIMEOUT);
}
if (runner != null) {
runner.interrupt();
}
onDone();
}
public boolean isCanceled() {
return state.get() >= CANCELLED;
}
public boolean isDone() {
return state.get() > RUNNING;
}
public Task<T> setDeliver(Executor deliver) {
this.deliver = deliver;
return this;
}
/**
* Scheduled task doesn't support timeout.
*/
public Task<T> setTimeout(final long timeoutMillis, final OnTimeoutListener listener) {
mTimeoutMillis = timeoutMillis;
mTimeoutListener = listener;
return this;
}
private void setSchedule(boolean isSchedule) {
this.isSchedule = isSchedule;
}
private Executor getDeliver() {
if (deliver == null) {
return getGlobalDeliver();
}
return deliver;
}
@CallSuper
protected void onDone() {
TASK_POOL_MAP.remove(this);
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
mTimeoutListener = null;
}
}
public interface OnTimeoutListener {
void onTimeout();
}
}
public static class SyncValue<T> {
private CountDownLatch mLatch = new CountDownLatch(1);
private AtomicBoolean mFlag = new AtomicBoolean();
private T mValue;
public void setValue(T value) {
if (mFlag.compareAndSet(false, true)) {
mValue = value;
mLatch.countDown();
}
}
public T getValue() {
if (!mFlag.get()) {
try {
mLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return mValue;
}
}
private static Executor getGlobalDeliver() {
if (sDeliver == null) {
sDeliver = new Executor() {
@Override
public void execute(@NonNull Runnable command) {
runOnUiThread(command);
}
};
}
return sDeliver;
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/analytics/utils/ThrowableUtils.java
|
package ai.datatower.analytics.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class ThrowableUtils {
private static final String LINE_SEP = System.getProperty("line.separator");
private ThrowableUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
public static String getFullStackTrace(Throwable throwable) {
final List<Throwable> throwableList = new ArrayList<>();
while (throwable != null && !throwableList.contains(throwable)) {
throwableList.add(throwable);
throwable = throwable.getCause();
}
final int size = throwableList.size();
final List<String> frames = new ArrayList<>();
List<String> nextTrace = getStackFrameList(throwableList.get(size - 1));
for (int i = size; --i >= 0; ) {
final List<String> trace = nextTrace;
if (i != 0) {
nextTrace = getStackFrameList(throwableList.get(i - 1));
removeCommonFrames(trace, nextTrace);
}
if (i == size - 1) {
frames.add(throwableList.get(i).toString());
} else {
frames.add(" Caused by: " + throwableList.get(i).toString());
}
frames.addAll(trace);
}
StringBuilder sb = new StringBuilder();
for (final String element : frames) {
sb.append(element).append(LINE_SEP);
}
return sb.toString();
}
private static List<String> getStackFrameList(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
final String stackTrace = sw.toString();
final StringTokenizer frames = new StringTokenizer(stackTrace, LINE_SEP);
final List<String> list = new ArrayList<>();
boolean traceStarted = false;
while (frames.hasMoreTokens()) {
final String token = frames.nextToken();
// Determine if the line starts with <whitespace>at
final int at = token.indexOf("at");
if (at != -1 && token.substring(0, at).trim().isEmpty()) {
traceStarted = true;
list.add(token);
} else if (traceStarted) {
break;
}
}
return list;
}
private static void removeCommonFrames(final List<String> causeFrames, final List<String> wrapperFrames) {
int causeFrameIndex = causeFrames.size() - 1;
int wrapperFrameIndex = wrapperFrames.size() - 1;
while (causeFrameIndex >= 0 && wrapperFrameIndex >= 0) {
// Remove the frame from the cause trace if it is the same
// as in the wrapper trace
final String causeFrame = causeFrames.get(causeFrameIndex);
final String wrapperFrame = wrapperFrames.get(wrapperFrameIndex);
if (causeFrame.equals(wrapperFrame)) {
causeFrames.remove(causeFrameIndex);
}
causeFrameIndex--;
wrapperFrameIndex--;
}
}
}
|
0
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/iap
|
java-sources/ai/datatower/core/3.2.0/ai/datatower/iap/utils/UUIDUtils.java
|
package ai.datatower.iap.utils;
import java.util.Random;
public class UUIDUtils {
public static String generateUUID() {
StringBuilder uuid = new StringBuilder();
for (int i = 0; i < 16; i++) {
uuid.append(Integer.toHexString(new Random().nextInt(16)));
}
return uuid.toString();
}
}
|
0
|
java-sources/ai/deepsense/seahorse-executor-deeplang_2.11/1.4.3/ai/deepsense/deeplang
|
java-sources/ai/deepsense/seahorse-executor-deeplang_2.11/1.4.3/ai/deepsense/deeplang/refl/Register.java
|
/*
* Copyright 2016 deepsense.ai (CodiLime, 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 ai.deepsense.deeplang.refl;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks the class to be registered in {@link ai.deepsense.deeplang.DOperation DOperation} catalog.
*
* @see ai.deepsense.deeplang.DOperation DOperation
*/
@Retention(RetentionPolicy.CLASS)
@Target({ ElementType.TYPE })
public @interface Register {
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/appium/SmartDriver.java
|
package ai.devtools.appium;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import ai.devtools.utils.CollectionUtils;
import ai.devtools.utils.JsonUtils;
import ai.devtools.utils.NetUtils;
import ai.devtools.utils.Utils;
import com.google.gson.JsonNull;
import io.appium.java_client.ios.IOSDriver;
import org.opencv.core.Core;
import org.opencv.imgcodecs.Imgcodecs;
import org.openqa.selenium.*;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.html5.Location;
import org.openqa.selenium.interactions.Keyboard;
import org.openqa.selenium.interactions.Mouse;
import org.openqa.selenium.interactions.Sequence;
import org.openqa.selenium.remote.*;
import org.openqa.selenium.json.Json;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.slf4j.helpers.MessageFormatter;
import com.google.gson.JsonObject;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
/**
* The {@code SmartDriver} class is a wrapper around a {@code RemoteWebDriver} that uses the results of the dev-tools.ai classifier for improved robustness, finding elements visually and avoiding broken selectors.
*/
@SuppressWarnings("deprecation")
public class SmartDriver<T extends MobileElement> {
/**
* The current version of the SDK
*/
private static String SDK_VERSION = "appium-0.1.20";
private boolean isMobileWeb = false;
public boolean isIOS;
public boolean isEspresso;
/**
* The logger for this class
*/
private Logger log = Logger.getLogger(SmartDriver.class);
/**
* The client to use for making http requests
*/
private OkHttpClient client;
/**
* The driver used by the user that we're wrapping.
*/
public AppiumDriver<T> driver;
/**
* The user's Smartdriver API key
*/
private String apiKey;
/**
* The base URL of the target server (e.g. {@code https://smartdriver.dev-tools.ai})
*/
private HttpUrl serverURL;
private String prodUrl = "https://smartdriver.dev-tools.ai";
/**
* The test case name. Used in live/interactive mode.
*/
private String testCaseName;
/**
* The UUID of the last screenshot in live/interactive mode.
*/
private String lastTestCaseScreenshotUUID;
/**
* The screen density multiplier
*/
public double multiplier;
private Dimension windowSize;
private Dimension imSize;
private Boolean useClassifierDuringCreation;
private Boolean testCaseCreationMode;
private String refScreenshotUUID;
private float pageOffset;
private float previousPageOffset;
private String automationName;
/**
* Constructor, creates a new SmartDriver.
*
* @param driver The {@code RemoteWebDriver} to wrap
* @param apiKey Your API key, acquired from <a href="https://smartdriver.dev-tools.ai">smartdriver.dev-tools.ai</a>.
* @param initializationDict The configuration options for the driver.
* @throws IOException If there was an initialization error.
*/
public SmartDriver(AppiumDriver<T> driver, String apiKey, Map<String, Object> initializationDict) throws IOException
{
this.driver = driver;
this.apiKey = apiKey;
log.setLevel(org.apache.log4j.Level.INFO);
BasicConfigurator.configure();
isIOS = driver instanceof IOSDriver;
Object automationNameObject = driver.getCapabilities().getCapability("automationName");
Object platformNameObject = driver.getCapabilities().getCapability("platformName");
String platformName = platformNameObject == null ? "": platformNameObject.toString();
String automationName = automationNameObject == null ? "": automationNameObject.toString();
if (automationName == "" && platformName == "Android") {
automationName = "UiAutomator2";
}
isEspresso = automationName.equals("Espresso");
//isMobileWeb = T instanceof RemoteWebElement;
this.testCaseName = (String) initializationDict.get("testCaseName");
this.useClassifierDuringCreation = true; // Default to running it because it's easier for customers
if (initializationDict.get("useClassifierDuringCreation") != null) {
this.useClassifierDuringCreation = (Boolean) initializationDict.get("useClassifierDuringCreation");
};
this.testCaseCreationMode = Utils.StrToBool(System.getenv("DEVTOOLSAI_INTERACTIVE"));
if (testCaseName == null)
{
StackTraceElement[] sl = Thread.currentThread().getStackTrace();
if (sl.length > 0)
{
StackTraceElement bottom = sl[sl.length - 1];
this.testCaseName = String.format("%s.%s", bottom.getClassName(), bottom.getMethodName());
log.info("No test case name was specified, defaulting to " + this.testCaseName);
}
else
this.testCaseName = "My first test case";
}
String baseUrl = (String) initializationDict.get("serverURL");
this.serverURL = HttpUrl.parse(baseUrl != null ? baseUrl : Objects.requireNonNullElse(System.getenv("DEVTOOLSAI_URL"), prodUrl));
client = this.serverURL.equals(HttpUrl.parse("https://smartdriver.dev-tools.ai")) ? NetUtils.unsafeClient() : NetUtils.basicClient().build();
BufferedImage im = ImageIO.read(driver.getScreenshotAs(OutputType.FILE));
imSize = new Dimension(im.getWidth(), im.getHeight());
if (isMobileWeb) {
float windowHeight = getWebWindowHeight();
float windowWidth = getWebWindowWidth();
windowSize = new Dimension((int) windowWidth, (int) windowHeight);
multiplier = 2.0;
} else {
windowSize = driver.manage().window().getSize();
multiplier = 1.0 * imSize.width / windowSize.width;
}
log.debug("The screen multiplier is " + multiplier);
try
{
JsonObject payload = CollectionUtils.keyValuesToJO("api_key", apiKey, "os",
String.format("%s-%s-%s", System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch")),
"sdk_version", SDK_VERSION,
"language", String.format("java-%s", System.getProperty("java.version")),
"test_case_name", this.testCaseName,
"automation_name", automationName);
log.debug(MessageFormatter.format("Checking in with: {}", payload.toString()).toString());
JsonObject r = JsonUtils.responseAsJson(NetUtils.basicPOST(client, this.serverURL, "ping", payload));
if (!JsonUtils.booleanFromJson(r, "success"))
log.debug(MessageFormatter.format("Error during checkin, server said: {}", r.toString()).getMessage());
}
catch (Throwable e)
{
log.debug(MessageFormatter.format("Checkin failed catastrophically: {}", e.getMessage()).getMessage());
}
}
private float getWebWindowHeight() {
JavascriptExecutor js = (JavascriptExecutor) driver;
Object res = js.executeScript("return window.innerHeight;");
if (res instanceof Number) {
return ((Number) res).floatValue();
} else {
return 0;
}
}
private float getWebWindowWidth() {
JavascriptExecutor js = (JavascriptExecutor) driver;
Object res = js.executeScript("return window.innerWidth;");
if (res instanceof Number) {
return ((Number) res).floatValue();
} else {
return 0;
}
}
/**
* Constructor, creates a new SmartDriver with the default server url (<a href="https://smartdriver.dev-tools.ai">smartdriver.dev-tools.ai</a>), non-interactive mode, and with training enabled.
*
* @param driver The {@code RemoteWebDriver} to wrap
* @param apiKey Your API key, acquired from <a href="https://smartdriver.dev-tools.ai">smartdriver.dev-tools.ai</a>.
* @throws IOException If there was an initialization error.
*/
public SmartDriver(AppiumDriver<T> driver, String apiKey) throws IOException
{
this(driver, apiKey, new HashMap<String, Object>());
}
/**
* Convenience method, implicitly wait for the specified amount of time.
*
* @param waitTime The number of seconds to implicitly wait.
* @return This {@code SmartDriver}, for chaining convenience.
*/
public SmartDriver implicitlyWait(long waitTime)
{
driver.manage().timeouts().implicitlyWait(waitTime, TimeUnit.SECONDS);
return this;
}
public org.openqa.selenium.remote.Response execute(String command)
{
return driver.execute(command);
}
public org.openqa.selenium.remote.Response execute(String command, Map<String, ?> parameters)
{
return driver.execute(command, parameters);
}
public String getContext()
{
return driver.getContext();
}
public Set<String> getContextHandles()
{
return driver.getContextHandles();
}
public ExecuteMethod getExecuteMethod()
{
return driver.getExecuteMethod();
}
public ScreenOrientation getOrientation()
{
return driver.getOrientation();
}
public URL getRemoteAddress()
{
return driver.getRemoteAddress();
}
public boolean isBrowser()
{
return driver.isBrowser();
}
public Location location()
{
return driver.location();
}
public void rotate(DeviceRotation rotation)
{
driver.rotate(rotation);
}
public void rotate(ScreenOrientation orientation)
{
driver.rotate(orientation);
}
public DeviceRotation rotation()
{
return driver.rotation();
}
public void setLocation(Location location)
{
driver.setLocation(location);
}
public Object executeAsyncScript(String script, Object... args)
{
return driver.executeAsyncScript(script, args);
}
public Object executeScript(String script, Object... args)
{
return driver.executeScript(script, args);
}
public Keyboard getKeyboard()
{
return driver.getKeyboard();
}
public Mouse getMouse()
{
return driver.getMouse();
}
public WebDriver.Options manage()
{
return driver.manage();
}
public WebDriver.Navigation navigate()
{
return driver.navigate();
}
public WebDriver.TargetLocator switchTo()
{
return driver.switchTo();
}
public void get(String url)
{
driver.get(url);
}
public T findElement(By locator, String elementName)
{
if (elementName == null) {
elementName = String.format("element_name_by_locator_%s", locator.toString().replace('.', '_').replace(' ', '_'));
}
try
{
T driverElement = driver.findElement(locator);
if (driverElement != null)
{
String key = uploadScreenshotIfNecessary(elementName, driverElement);
if (key != null) {
updateElement(driverElement, key, elementName, true);
}
}
return driverElement;
}
catch (Throwable x)
{
log.info(MessageFormatter.format("Element '{}' was not found by Selenium, trying with Smartdriver...", elementName).getMessage());
ClassifyResult<T> result = classify(elementName);
if (result.e != null) {
return result.e.realElement;
} else {
log.error(result.msg);
}
log.error(MessageFormatter.format("Smartdriver was also unable to find the element with name '{}'", elementName).getMessage());
throw x;
}
}
public MobileElement findElement(By locator)
{
return findElement(locator, null);
}
public List<T> findElements(By locator)
{
return driver.findElements(locator);
}
public Capabilities getCapabilities()
{
return driver.getCapabilities();
}
public CommandExecutor getCommandExecutor()
{
return driver.getCommandExecutor();
}
public String getCurrentUrl()
{
return driver.getCurrentUrl();
}
public ErrorHandler getErrorHandler()
{
return driver.getErrorHandler();
}
public FileDetector getFileDetector()
{
return driver.getFileDetector();
}
public String getPageSource()
{
return driver.getPageSource();
}
public <X> X getScreenshotAs(OutputType<X> outputType)
{
return driver.getScreenshotAs(outputType);
}
public SessionId getSessionId()
{
return driver.getSessionId();
}
public String getTitle()
{
return driver.getTitle();
}
public String getWindowHandle()
{
return driver.getWindowHandle();
}
public Set<String> getWindowHandles()
{
return driver.getWindowHandles();
}
public void perform(Collection<Sequence> actions)
{
driver.perform(actions);
}
public void quit()
{
driver.quit();
}
public void resetInputState()
{
driver.resetInputState();
}
public void setErrorHandler(ErrorHandler handler)
{
driver.setErrorHandler(handler);
}
public void setFileDetector(FileDetector detector)
{
driver.setFileDetector(detector);
}
public void setLogLevel(Level level)
{
driver.setLogLevel(level);
}
public String toString()
{
return driver.toString();
}
/**
* Attempts to find an element by class name.
*
* @param using The class name of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByClassName(String using, String elementName)
{
return this.findElement(By.className(using), elementName);
}
/**
* Attempts to find an element by class name.
*
* @param using The class name of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByClassName(String using)
{
return findElementByClassName(using, null);
}
/**
* Attempts to find all elements with the matching class name.
*
* @param using The class name of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<T> findElementsByClassName(String using)
{
return driver.findElements(By.className(using));
}
/**
* Attempts to find an element by css selector.
*
* @param using The css selector of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByCssSelector(String using, String elementName)
{
return this.findElement(By.cssSelector(using), elementName);
}
/**
* Attempts to find an element by css selector.
*
* @param using The css selector of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByCssSelector(String using)
{
return findElementByCssSelector(using, null);
}
/**
* Attempts to find all elements with the matching css selector.
*
* @param using The css selector of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<T> findElementsByCssSelector(String using)
{
return driver.findElements(By.cssSelector(using));
}
/**
* Attempts to find an element by id.
*
* @param using The id of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementById(String using, String elementName)
{
return findElement(By.id(using), elementName);
}
/**
* Attempts to find an element by id.
*
* @param using The id of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementById(String using)
{
return findElementById(using, null);
}
/**
* Attempts to find all elements with the matching id.
*
* @param using The id of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<T> findElementsById(String using)
{
return driver.findElements(By.id(using));
}
/**
* Attempts to find an element by link text.
*
* @param using The link text of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByLinkText(String using, String elementName)
{
return findElement(By.linkText(using), elementName);
}
/**
* Attempts to find an element by link text.
*
* @param using The link text of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByLinkText(String using)
{
return findElementByLinkText(using, null);
}
/**
* Attempts to find all elements with the matching link text.
*
* @param using The link text of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<T> findElementsByLinkText(String using)
{
return driver.findElements(By.linkText(using));
}
/**
* Attempts to find an element by name.
*
* @param using The name of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByName(String using, String elementName)
{
return findElement(By.name(using), elementName);
}
/**
* Attempts to find an element by name.
*
* @param using The name of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByName(String using)
{
return findElementByName(using, null);
}
/**
* Attempts to find all elements with the matching name.
*
* @param using The name of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<T> findElementsByName(String using)
{
return driver.findElements(By.name(using));
}
/**
* Attempts to find an element by partial link text.
*
* @param using The partial link text of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByPartialLinkText(String using, String elementName)
{
return findElement(By.partialLinkText(using), elementName);
}
/**
* Attempts to find an element by partial link text.
*
* @param using The partial link text of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByPartialLinkText(String using)
{
return findElementByPartialLinkText(using, null);
}
/**
* Attempts to find all elements with the matching partial link text.
*
* @param using The partial link text of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<T> findElementsByPartialLinkText(String using)
{
return driver.findElements(By.partialLinkText(using));
}
/**
* Attempts to find an element by tag name.
*
* @param using The tag name of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByTagName(String using, String elementName)
{
return findElement(By.tagName(using), elementName);
}
/**
* Attempts to find an element by tag name.
*
* @param using The tag name of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByTagName(String using)
{
return findElementByTagName(using, null);
}
/**
* Attempts to find all elements with the matching tag name.
*
* @param using The tag name of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<T> findElementsByTagName(String using)
{
return driver.findElements(By.tagName(using));
}
/**
* Attempts to find an element by xpath.
*
* @param using The xpath of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByXPath(String using, String elementName)
{
return findElement(By.xpath(using), elementName);
}
/**
* Attempts to find an element by xpath.
*
* @param using The xpath of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public T findElementByXPath(String using)
{
return findElementByXPath(using, null);
}
/**
* Attempts to find all elements with the matching xpath.
*
* @param using The xpath of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<T> findElementsByXPath(String using)
{
return driver.findElements(By.xpath(using));
}
/**
* Finds an element by {@code elementName}. Please use {@link #findElementByElementName(String)} instead.
*
* @param elementName The label name of the element to be classified.
* @return An element associated with {@code elementName}. Throws NoSuchElementException otherwise.
*/
public T findByElementName(String elementName)
{
return findElementByElementName(elementName);
}
/**
* Finds an element by {@code elementName}.
*
* @param elementName The label name of the element to be classified.
* @return An element associated with {@code elementName}. Throws NoSuchElementException otherwise.
*/
public T findElementByElementName(String elementName)
{
ClassifyResult<T> r = classify(elementName);
if (r.e == null)
throw new NoSuchElementException(r.msg);
return r.e.realElement;
}
/**
* Finds an elements by {@code elementName}. Uses visual AI to find the element.
*
* @param elementName The label name of the element to be classified.
* @return An element associated with {@code elementName}. Throws NoSuchElementException otherwise.
*/
public T findByAI(String elementName)
{
return findElementByElementName(elementName);
}
private String getScreenshotHash(String screenshotBase64) {
try {
/* the following code does not work because ImageIO.write does not create the same output as cv2 for the same b64 image, so the hashes are not good
// Convert b64 image to buffered image, crop top 85 pixels, convert back to b64
BufferedImage image = null;
image = ImageIO.read(new ByteArrayInputStream(
Base64.getDecoder().decode(screenshotBase64.replaceAll("\\r\\n|\\r|\\n", ""))));
image = image.getSubimage(0, 85, image.getWidth(), image.getHeight() - 85);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", baos);
screenshotBase64 = Base64.getEncoder().encodeToString(baos.toByteArray());
*/
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5sum = md.digest(screenshotBase64.getBytes(StandardCharsets.UTF_8));
String output = String.format("%032X", new BigInteger(1, md5sum));
return output.toLowerCase();
} catch (Throwable e) {
return "";
}
}
private JsonObject checkScreenshotExists(String screenshotUUID, String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot_uuid", screenshotUUID);
payload.add("stack_trace", Utils.collectStackTrace());
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "exists_screenshot", payload));
return res;
} catch (Throwable e) {
log.debug("Error checking if screenshot exists");
e.printStackTrace();
return null;
}
}
private JsonObject uploadScreenshot(String screenshotBase64,String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
payload.addProperty("is_appium", true);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "upload_screenshot", payload));
return res;
} catch (Throwable e) {
log.debug("Error uploading screenshot");
e.printStackTrace();
return null;
}
}
private JsonObject uploadTCScreenshot(String screenshotBase64, String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
payload.addProperty("is_interactive", true);
payload.addProperty("is_appium", true);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "upload_screenshot", payload));
return res;
} catch (Throwable e) {
log.debug("Error uploading test case screenshot");
e.printStackTrace();
return null;
}
}
public void scrollToElement(T element, Boolean scrollUp) {
/*
if(scrollUp) {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(false);", element);
} else {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
}*/
}
public void scrollPage(int amount) {
/*
((JavascriptExecutor) driver).executeScript("window.scrollBy(0, " + amount + ")");
*/
}
private String uploadScreenshotIfNecessary(String elementName, T element) {
Boolean isElementFrozen = checkIfFrozen(elementName);
if (isElementFrozen) {
return null;
} else {
String screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
String screenshotUUID = getScreenshotHash(screenshotBase64);
refScreenshotUUID = null;
pageOffset = 0f;
if (element != null) {
pageOffset = getPageOffset();
Boolean needsToScroll = (element.getRect().getY() > (windowSize.getHeight() + pageOffset)) || (element.getRect().getY() < pageOffset);
if(needsToScroll) {
previousPageOffset = pageOffset;
refScreenshotUUID = screenshotUUID;
scrollToElement(element, element.getRect().getY() < pageOffset);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
screenshotUUID = getScreenshotHash(screenshotBase64);
pageOffset = getPageOffset();
scrollPage((int) (previousPageOffset - pageOffset));
}
}
JsonObject screenshotExistsResponse = checkScreenshotExists(screenshotUUID, elementName);
if (screenshotExistsResponse != null && screenshotExistsResponse.get("exists_screenshot").getAsBoolean()) {
return screenshotUUID;
} else {
JsonObject uploadScreenshotResponse = uploadScreenshot(screenshotBase64, elementName);
if (uploadScreenshotResponse != null) {
if (uploadScreenshotResponse.get("success").getAsBoolean()) {
return uploadScreenshotResponse.get("screenshot_uuid").getAsString();
} else {
log.info("Error uploading screenshot");
return screenshotUUID;
}
} else {
log.info("Error uploading screenshot");
return screenshotUUID;
}
}
}
}
private Boolean checkIfFrozen(String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "check_frozen", payload));
return res.get("is_frozen").getAsBoolean();
} catch (Throwable e) {
log.debug("Error checking if element is frozen");
e.printStackTrace();
return true;
}
}
/**
* Shared {@code findElementBy} functionality. This serves as the base logic for most find by methods exposed to the end user.
*
* @param using The search term to use when looking for an element.
* @param elementName The label name of the element to be classified. This is what the element will be stored under in the dev-tools.ai db.
* @param shortcode The short identifier for the type of lookup being performed. This will be used to aut-generate an {@code elementName} if the user did not specify one.
* @param fn The selenium function to call with {@code using}, which will be used to fetch what selenium thinks is the target element.
* @return The SmartDriverElement
*/
private T findElementByGeneric(String using, String elementName, String shortcode, Function<String, T> fn)
{
if (elementName == null) {
elementName = String.format("element_name_by_%s_%s", shortcode, using.replace('.', '_'));
}
try
{
T driverElement = fn.apply(using);
if (driverElement != null)
{
String key = uploadScreenshotIfNecessary(elementName, driverElement);
if (key != null) {
updateElement(driverElement, key, elementName, true);
}
}
return driverElement;
}
catch (Throwable x)
{
log.info(MessageFormatter.format("Element '{}' was not found by Selenium, trying with Smartdriver...", elementName).getMessage());
ClassifyResult<T> result = classify(elementName);
if (result.e != null) {
return result.e.realElement;
} else {
log.error(result.msg);
}
log.error(MessageFormatter.format("Smartdriver was also unable to find the element with name '{}'", elementName).getMessage());
throw x;
}
}
/**
* Updates the entry for an element as it is known to the dev-tools.ai servers.
*
* @param elem The element to update
* @param screenshotUUID The key associated with this element
* @param elementName The name associated with this element
* @param trainIfNecessary Set {@code true} if the model on the server should also be trained with this element.
*/
protected void updateElement(T elem, String screenshotUUID, String elementName, boolean trainIfNecessary)
{
Rectangle rect = elem.getRect();
JsonObject payload = new JsonObject();
payload.addProperty("screenshot_uuid", screenshotUUID);
payload.addProperty("retrain", trainIfNecessary);
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("x", rect.x * multiplier);
payload.addProperty("y", rect.y * multiplier);
payload.addProperty("width", rect.width * multiplier);
payload.addProperty("height", rect.height * multiplier);
payload.addProperty("multiplier", multiplier);
payload.addProperty("test_case_name", testCaseName);
payload.addProperty("page_offset", this.pageOffset * this.multiplier);
payload.addProperty("ref_screenshot_uuid", this.refScreenshotUUID);
try {
JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "add_action_info", payload));
} catch (Throwable e) {
log.debug("Error updating element");
e.printStackTrace();
}
}
private CollectionUtils.Tuple<JsonObject, Boolean> getTCBox(String elementName, String eventUUID) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot_uuid", lastTestCaseScreenshotUUID);
payload.addProperty("run_classifier", useClassifierDuringCreation);
payload.addProperty("event_id", eventUUID);
payload.add("stack_trace", Utils.collectStackTrace());
Boolean needsReload = false;
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "testcase/get_action_info", payload));
needsReload = res.get("needs_reload").getAsBoolean();
return new CollectionUtils.Tuple<>(res, needsReload);
} catch (Throwable e) {
log.debug("Error getting TC box");
e.printStackTrace();
return new CollectionUtils.Tuple<>(null, needsReload);
}
}
private void openBrowser(String url) {
try {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("mac")) {
Runtime.getRuntime().exec("open " + url);
} else if (os.contains("windows")) {
Runtime.getRuntime().exec("run " + url);
} else {
log.info(MessageFormatter.format("Please open the following URL in your browser: {}", url).getMessage());
}
} catch (Throwable e) {
log.info(MessageFormatter.format("Please open the following URL in your browser: {}", url).getMessage());
}
}
/**
* Perform additional classification on an element by querying the dev-tools.ai server.
*
* @param elementName The name of the element to run classification on.
* @return The result of the classification.
*/
protected ClassifyResult<T> classify(String elementName)
{
if(testCaseCreationMode) {
String screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
JsonObject res = uploadTCScreenshot(screenshotBase64, elementName);
if (res.get("success").getAsBoolean()) {
lastTestCaseScreenshotUUID = res.get("screenshot_uuid").getAsString();
CollectionUtils.Tuple<JsonObject, Boolean> boxResponseTp = getTCBox(elementName, null);
JsonObject boxResponse = boxResponseTp.k;
Boolean needsReload = boxResponseTp.v;
if (boxResponse != null && boxResponse.get("success").getAsBoolean() && boxResponse.get("predicted_element") != JsonNull.INSTANCE) {
return new ClassifyResult(new SmartDriverElement(boxResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()), lastTestCaseScreenshotUUID);
} else {
// label_url = self.url + '/testcase/label?test_case_name=' + urllib.parse.quote(self.test_case_uuid)
// generate a uuid
String eventUUID = UUID.randomUUID().toString();
String labelUrl = serverURL + "/testcase/label?test_case_name=" + URLEncoder.encode(testCaseName) + "&event_id=" + eventUUID + "&api_key=" + apiKey;
openBrowser(labelUrl);
while (true) {
boxResponseTp = getTCBox(elementName, eventUUID);
boxResponse = boxResponseTp.k;
needsReload = boxResponseTp.v;
if (boxResponse != null && boxResponse.get("success").getAsBoolean() && boxResponse.get("predicted_element") != JsonNull.INSTANCE) {
return new ClassifyResult(new SmartDriverElement(boxResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()), lastTestCaseScreenshotUUID);
}
if (needsReload) {
screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
uploadTCScreenshot(screenshotBase64, elementName);
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} else {
log.info("Failed to upload test case screenshot");
log.info(res.get("message").getAsString());
return new ClassifyResult(null, lastTestCaseScreenshotUUID, res.get("message").getAsString());
}
} else {
String pageSource = "", msg = "Smartdriver driver exception", key = null;
try {
String screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
String screenshotUUID = getScreenshotHash(screenshotBase64);
JsonObject screenshotExistsResponse = checkScreenshotExists(screenshotUUID, elementName);
if (screenshotExistsResponse != null && screenshotExistsResponse.get("success").getAsBoolean() && screenshotExistsResponse.get("predicted_element") != JsonNull.INSTANCE) {
msg = screenshotExistsResponse.get("message").getAsString();
log.info(msg);
float currentOffset = getPageOffset();
float bottomOffset = currentOffset + windowSize.height;
float realOffset = (float) (screenshotExistsResponse.get("page_offset").getAsFloat() / multiplier);
if (realOffset > bottomOffset || realOffset < currentOffset) {
int scrollOffset = (int) (realOffset - currentOffset);
// Scroll
scrollPage((int) scrollOffset);
Thread.sleep(1000);
screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
screenshotUUID = getScreenshotHash(screenshotBase64);
screenshotExistsResponse = checkScreenshotExists(screenshotUUID, elementName);
}
if (screenshotExistsResponse != null && screenshotExistsResponse.get("success").getAsBoolean() && screenshotExistsResponse.get("predicted_element") != JsonNull.INSTANCE) {
return new ClassifyResult(new SmartDriverElement(screenshotExistsResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()), null);
}
}
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
payload.add("stack_trace", Utils.collectStackTrace());
JsonObject classifyResponse = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "detect", payload));
if (!classifyResponse.get("success").getAsBoolean()) {
classifyResponse = classifyFullScreen(elementName, screenshotBase64);
if (!classifyResponse.get("success").getAsBoolean()) {
log.info(classifyResponse.get("message").getAsString());
return new ClassifyResult(null, null, classifyResponse.get("message").getAsString());
}
}
msg = classifyResponse.get("message").getAsString().replace(prodUrl, serverURL.toString());
log.info(msg);
try {
return new ClassifyResult(new SmartDriverElement(classifyResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()),
classifyResponse.get("screenshot_uuid").getAsString());
} catch (Throwable e) {
log.error("Error creating SmartDriverElement from response");
e.printStackTrace();
return new ClassifyResult(null, key, msg);
}
} catch (Throwable e) {
e.printStackTrace();
}
log.warn(msg);
return new ClassifyResult(null, key, msg);
}
}
private float getPageOffset(){
/*
Object res = driver.executeScript("return window.pageYOffset;");
if (res instanceof Number) {
return ((Number) res).floatValue();
} else {
return 0;
}
*/
return 0;
}
JsonObject classifyFullScreen(String elementName, String screenshotBase64) {
int lastOffset = -1;
int offset = 1;
int windowHeight = windowSize.height;
scrollPage(-100000);
JsonObject r = new JsonObject();
r.addProperty("success", false);
while(offset > lastOffset) {
lastOffset = offset;
screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
payload.add("stack_trace", Utils.collectStackTrace());
try {
r = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "detect", payload));
if (r.get("success").getAsBoolean() || !isMobileWeb) {
return r;
}
} catch (Throwable e) {
log.error("Error creating SmartDriverElement from response");
e.printStackTrace();
return r;
}
scrollPage((int) windowHeight);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
offset = (int) getPageOffset();
}
return r;
}
/**
* Simple container for encapsulating results of calls to {@code classify()}.
*
*/
private static class ClassifyResult<T extends MobileElement>
{
/**
* The SmartDriverElement created by the call to classify
*/
public SmartDriverElement<T> e;
/**
* The key returned by the call to classify
*/
public String key;
/**
* The message associated with this result
*/
public String msg;
/**
* Constructor, creates a new ClassifyResult.
*
* @param e The SmartDriverElement to to use
* @param key The key to use
* @param msg The message to associate with this result
*/
ClassifyResult(SmartDriverElement<T> e, String key, String msg)
{
this.e = e;
this.key = key;
this.msg = msg;
}
/**
* Constructor, creates a new ClassifyResult, where the {@code msg} is set to the empty String by default.
*
* @param e
* @param key
*/
ClassifyResult(SmartDriverElement<T> e, String key)
{
this(e, key, "");
}
}
public void close() {
driver.close();
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/appium/SmartDriverElement.java
|
package ai.devtools.appium;
import ai.devtools.utils.JsonUtils;
import ai.devtools.utils.MatchUtilsAppium;
import com.google.gson.JsonObject;
import java.util.List;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.Rectangle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An enhanced RemoteWebElement which uses the results of the dev-tools.ai classifier for improved accuracy.
*
*/
public class SmartDriverElement<T extends MobileElement> extends MobileElement
{
/**
* The logger for this class
*/
private static Logger log = LoggerFactory.getLogger(SmartDriverElement.class);
/**
* The webdriver the user is using. We wrap this for when the user calls methods that interact with selenium.
*/
private AppiumDriver<T> driver;
/**
* The underlying {@code WebElement} used for performing actions in the browser.
*/
public T realElement;
/**
* The text in this element, as determined by dev-tools.ai's classifier
*/
private String text;
/**
* The size of this element, in pixels
*/
private Dimension size;
/**
* The location of this element, in pixels (offset from the upper left corner of the screen)
*/
private Point location;
/**
* The rectangle that can be drawn around this element. Basically combines size and location.
*/
private Rectangle rectangle;
/**
* The tag name of this element, as determined by dev-tools.ai's classifier
*/
private String tagName;
SmartDriverElement(JsonObject elem, SmartDriver<T> driver) {
this(elem, driver, 0);
}
/**
* Constructor, creates a new SmartDriverElement
*
* @param elem The element data returned by the FD API, as JSON
* @param driver The {@code SmartDriver} to associate with this {@code SmartDriverElement}.
*/
SmartDriverElement(JsonObject elem, SmartDriver<T> driver, float page_offset)
{
log.debug("Creating new SmartDriverElement w/ {}", elem);
this.driver = driver.driver;
int pageY = elem.get("y").getAsInt();
elem.remove("y");
elem.addProperty("y", pageY + page_offset * driver.multiplier);
this.realElement = new MatchUtilsAppium<T>().matchBoundingBoxToAppiumElement(elem, driver);
text = JsonUtils.stringFromJson(elem, "text");
size = new Dimension(JsonUtils.intFromJson(elem, "width") / Math.max((int) driver.multiplier, 1), JsonUtils.intFromJson(elem, "height") / Math.max((int) driver.multiplier, 1));
location = new Point(JsonUtils.intFromJson(elem, "x") / Math.max((int) driver.multiplier, 1), JsonUtils.intFromJson(elem, "y") / Math.max((int) driver.multiplier, 1));
// this.property = property //TODO: not referenced/implemented on python side??
rectangle = new Rectangle(location, size);
tagName = JsonUtils.stringFromJson(elem, "class");
}
public String toString()
{
return "SmartDriverElement: " + text;
}
@Override
public String getText()
{
return text;
}
@Override
public Dimension getSize()
{
return size;
}
@Override
public Point getLocation()
{
return location;
}
@Override
public Rectangle getRect()
{
return rectangle;
}
@Override
public String getTagName()
{
return tagName;
}
@Override
public void clear()
{
realElement.clear();
}
@Override
public T findElement(By by)
{
return driver.findElement(by);
}
/* TODO
@Override
public List<MobileElement> findElements(By by)
{
return (List<MobileElement>) driver.findElements(by);
}*/
@Override
public String getAttribute(String name)
{
return realElement.getAttribute(name);
}
@Override
public String getCssValue(String propertyName)
{
return realElement.getCssValue(propertyName);
}
@Override
public boolean isDisplayed()
{
return realElement.isDisplayed();
}
@Override
public boolean isEnabled()
{
return realElement.isEnabled();
}
@Override
public boolean isSelected()
{
return realElement.isSelected();
}
@Override
public void click()
{
realElement.click();
}
@Override
public void sendKeys(CharSequence... keysToSend)
{
realElement.sendKeys(keysToSend);
}
@Override
public void submit()
{
realElement.submit();
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/selenium/By.java
|
package ai.devtools.selenium;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
import java.util.List;
public abstract class By extends org.openqa.selenium.By {
public static By ai(String elementName) {
return new ByAI(elementName);
}
public static By ai(String elementName, Float customAIThreshold) {
return new ByAI(elementName, customAIThreshold);
}
public static class ByAI extends By {
public final String aiElementName;
public Float customAIThreshold;
public ByAI(String elementName) {
this.aiElementName = elementName;
}
public ByAI(String elementName, Float customAIThreshold) {
this.aiElementName = elementName;
this.customAIThreshold = customAIThreshold;
}
@Override
public List<WebElement> findElements(SearchContext searchContext) {
return ((SmartDriver) searchContext).findElementsByAI(this.aiElementName, this.customAIThreshold );
}
@Override
public WebElement findElement(SearchContext searchContext) {
return ((SmartDriver) searchContext).findElementByAI(this.aiElementName, this.customAIThreshold);
}
@Override
public String toString() {
return "By.ai: " + aiElementName;
}
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/selenium/SmartDriver.java
|
package ai.devtools.selenium;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.logging.Level;
import java.awt.Desktop;
import java.net.URI;
import javax.imageio.ImageIO;
import ai.devtools.utils.CollectionUtils;
import ai.devtools.utils.JsonUtils;
import ai.devtools.utils.NetUtils;
import ai.devtools.utils.Utils;
import com.google.gson.JsonNull;
import org.openqa.selenium.*;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.interactions.Sequence;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.ErrorHandler;
import org.openqa.selenium.remote.FileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.SessionId;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.slf4j.helpers.MessageFormatter;
import com.google.gson.JsonObject;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
/**
* The {@code SmartDriver} class is a wrapper around a {@code RemoteWebDriver} that uses the results of the dev-tools.ai classifier for improved robustness, finding elements visually and avoiding broken selectors.
*/
@SuppressWarnings("deprecation")
public class SmartDriver extends RemoteWebDriver {
/**
* The current version of the SDK
*/
private static String SDK_VERSION = "selenium-0.1.20";
/**
* The logger for this class
*/
private Logger log = Logger.getLogger(SmartDriver.class);
/**
* The client to use for making http requests
*/
private OkHttpClient client;
/**
* The driver used by the user that we're wrapping.
*/
public RemoteWebDriver driver;
/**
* The user's Smartdriver API key
*/
private String apiKey;
/**
* The base URL of the target server (e.g. {@code https://smartdriver.dev-tools.ai})
*/
private HttpUrl serverURL;
private String prodUrl = "https://smartdriver.dev-tools.ai";
/**
* The test case name. Used in live/interactive mode.
*/
private String testCaseName;
/**
* The UUID of the last screenshot in live/interactive mode.
*/
private String lastTestCaseScreenshotUUID;
/**
* The screen density multiplier
*/
public double multiplier;
private Dimension windowSize;
private Dimension imSize;
private Boolean useClassifierDuringCreation;
private Boolean testCaseCreationMode;
private String refScreenshotUUID;
private float pageOffset;
private float previousPageOffset;
private String automationName;
public boolean UseJSChopper = false;
private int classifyMaxRetries = 3;
/**
* Constructor, creates a new SmartDriver.
*
* @param driver The {@code RemoteWebDriver} to wrap
* @param apiKey Your API key, acquired from <a href="https://smartdriver.dev-tools.ai">smartdriver.dev-tools.ai</a>.
* @param initializationDict The configuration options for the driver.
* @throws IOException If there was an initialization error.
*/
public SmartDriver(RemoteWebDriver driver, String apiKey, Map<String, Object> initializationDict) throws IOException
{
this.driver = driver;
this.apiKey = apiKey;
log.setLevel(org.apache.log4j.Level.INFO);
BasicConfigurator.configure();
this.testCaseName = (String) initializationDict.get("testCaseName");
this.useClassifierDuringCreation = true; // Default to running it because it's easier for customers
this.UseJSChopper = initializationDict.get("useFastJsChopper") == null ? false : (Boolean) initializationDict.get("useFastJsChopper");
this.classifyMaxRetries = initializationDict.get("classifyMaxRetries") == null ? 3 : (Integer) initializationDict.get("classifyMaxRetries");
if (initializationDict.get("useClassifierDuringCreation") != null) {
this.useClassifierDuringCreation = (Boolean) initializationDict.get("useClassifierDuringCreation");
};
this.testCaseCreationMode = Utils.StrToBool(System.getenv("DEVTOOLSAI_INTERACTIVE"));
Object automationNameObject = driver.getCapabilities().getCapability("browserName");
automationName = automationNameObject == null ? "": automationNameObject.toString();
if (testCaseName == null)
{
StackTraceElement[] sl = Thread.currentThread().getStackTrace();
if (sl.length > 0)
{
StackTraceElement bottom = sl[sl.length - 1];
this.testCaseName = String.format("%s.%s", bottom.getClassName(), bottom.getMethodName());
log.info("No test case name was specified, defaulting to " + this.testCaseName);
}
else
this.testCaseName = "My first test case";
}
String baseUrl = (String) initializationDict.get("serverURL");
this.serverURL = HttpUrl.parse(baseUrl != null ? baseUrl : Objects.requireNonNullElse(System.getenv("DEVTOOLSAI_URL"), prodUrl));
client = this.serverURL.equals(HttpUrl.parse("https://smartdriver.dev-tools.ai")) ? NetUtils.unsafeClient() : NetUtils.basicClient().build();
windowSize = driver.manage().window().getSize();
BufferedImage im = ImageIO.read(driver.getScreenshotAs(OutputType.FILE));
imSize = new Dimension(im.getWidth(), im.getHeight());
multiplier = 1.0 * imSize.width / windowSize.width;
log.debug("The screen multiplier is " + multiplier);
try
{
JsonObject payload = CollectionUtils.keyValuesToJO("api_key", apiKey, "os",
String.format("%s-%s-%s", System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")), "sdk_version", SDK_VERSION, "language",
String.format("java-%s", System.getProperty("java.version")),
"test_case_name", this.testCaseName,
"automation_name", automationName);
log.debug(MessageFormatter.format("Checking in with: {}", payload.toString()).toString());
JsonObject r = JsonUtils.responseAsJson(NetUtils.basicPOST(client, this.serverURL, "ping", payload));
if (!JsonUtils.booleanFromJson(r, "success"))
log.debug(MessageFormatter.format("Error during checkin, server said: {}", r.toString()).getMessage());
}
catch (Throwable e)
{
log.debug(MessageFormatter.format("Checkin failed catastrophically: {}", e.getMessage()).getMessage());
}
}
/**
* Constructor, creates a new SmartDriver with the default server url (<a href="https://smartdriver.dev-tools.ai">smartdriver.dev-tools.ai</a>), non-interactive mode, and with training enabled.
*
* @param driver The {@code RemoteWebDriver} to wrap
* @param apiKey Your API key, acquired from <a href="https://smartdriver.dev-tools.ai">smartdriver.dev-tools.ai</a>.
* @throws IOException If there was an initialization error.
*/
public SmartDriver(RemoteWebDriver driver, String apiKey) throws IOException
{
this(driver, apiKey, new HashMap<String, Object>());
}
/**
* Convenience method, implicitly wait for the specified amount of time.
*
* @param waitTime The number of seconds to implicitly wait.
* @return This {@code SmartDriver}, for chaining convenience.
*/
public SmartDriver implicitlyWait(long waitTime)
{
driver.manage().timeouts().implicitlyWait(waitTime, TimeUnit.SECONDS);
return this;
}
@Override
public Object executeAsyncScript(String script, Object... args)
{
return driver.executeAsyncScript(script, args);
}
@Override
public Object executeScript(String script, Object... args)
{
return driver.executeScript(script, args);
}
/**
* Opens a web browser and directs it to {@code url}.
*
* @param url The URL to launch the browser to.
*/
@Override
public void get(String url)
{
driver.get(url);
}
public WebElement findElement(org.openqa.selenium.By locator, String elementName) {
return findElement(locator, elementName, null);
}
public WebElement findElement(org.openqa.selenium.By locator, Float customAIThreshold) {
return findElement(locator, null, customAIThreshold);
}
public WebElement findElement(org.openqa.selenium.By locator, String elementName, Float customAIThreshold)
{
Float optionalThreshold = customAIThreshold;
if (elementName == null) {
// If it's a By.ai element, use the name of the element
if (locator instanceof By.ByAI) {
elementName = ((By.ByAI) locator).aiElementName;
} else {
elementName = String.format("element_name_by_locator_%s", locator.toString().replace('.', '_').replace(' ', '_'));
}
}
try
{ WebElement driverElement = null;
if (!(locator instanceof By.ByAI)) {
driverElement = driver.findElement(locator);
} else {
optionalThreshold = ((By.ByAI) locator).customAIThreshold;
throw new NoSuchElementException("Search by AI");
}
if (driverElement != null)
{
String key = uploadScreenshotIfNecessary(elementName, driverElement);
if (key != null) {
updateElement(driverElement, key, elementName, true);
}
}
return driverElement;
}
catch (Throwable x)
{
log.info(MessageFormatter.format("Element '{}' was not found by Selenium, trying with Smartdriver...", elementName).getMessage());
// Do 3 retries on classify on failure
for(int i = 0; i < classifyMaxRetries; i++) {
ClassifyResult result = classify(elementName, optionalThreshold);
if (result.e != null) {
return result.e;
} else {
if(i == classifyMaxRetries - 1) {
log.error(result.msg);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.error(MessageFormatter.format("Smartdriver was also unable to find the element with name '{}'", elementName).getMessage());
throw x;
}
}
public WebElement findElement(org.openqa.selenium.By locator)
{
return findElement(locator, null, null);
}
public List<WebElement> findElements(By locator)
{
return driver.findElements(locator);
}
public List<WebElement> findElementsByAI(String elementName) {
// For now only returns one element
WebElement e = findByAI(elementName);
if (e != null) {
return Arrays.asList(e);
} else {
return new ArrayList<WebElement>();
}
}
public List<WebElement> findElementsByAI(String elementName, Float customAIThreshold) {
// For now only returns one element
WebElement e = findByAI(elementName, customAIThreshold);
if (e != null) {
return Arrays.asList(e);
} else {
return new ArrayList<WebElement>();
}
}
public WebElement findElementByAI(String elementName) {
return findByAI(elementName);
}
public WebElement findElementByAI(String elementName, Float customAIThreshold) {
return findByAI(elementName, customAIThreshold);
}
@Override
public Capabilities getCapabilities()
{
return driver.getCapabilities();
}
@Override
public CommandExecutor getCommandExecutor()
{
return driver.getCommandExecutor();
}
@Override
public String getCurrentUrl()
{
return driver.getCurrentUrl();
}
@Override
public ErrorHandler getErrorHandler()
{
return driver.getErrorHandler();
}
@Override
public FileDetector getFileDetector()
{
return driver.getFileDetector();
}
@Override
public String getPageSource()
{
return driver.getPageSource();
}
@Override
public <X> X getScreenshotAs(OutputType<X> outputType)
{
return driver.getScreenshotAs(outputType);
}
@Override
public SessionId getSessionId()
{
return driver.getSessionId();
}
@Override
public String getTitle()
{
return driver.getTitle();
}
@Override
public String getWindowHandle()
{
return driver.getWindowHandle();
}
@Override
public Set<String> getWindowHandles()
{
return driver.getWindowHandles();
}
@Override
public Options manage()
{
return driver.manage();
}
@Override
public Navigation navigate()
{
return driver.navigate();
}
@Override
public void perform(Collection<Sequence> actions)
{
driver.perform(actions);
}
@Override
public void quit()
{
driver.quit();
}
@Override
public void resetInputState()
{
driver.resetInputState();
}
@Override
public void setErrorHandler(ErrorHandler handler)
{
driver.setErrorHandler(handler);
}
@Override
public void setFileDetector(FileDetector detector)
{
driver.setFileDetector(detector);
}
@Override
public void setLogLevel(Level level)
{
driver.setLogLevel(level);
}
@Override
public TargetLocator switchTo()
{
return driver.switchTo();
}
@Override
public String toString()
{
return driver.toString();
}
/**
* Attempts to find an element by class name.
*
* @param using The class name of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByClassName(String using, String elementName)
{
return this.findElement(By.className(using), elementName);
}
public WebElement findElementByClassName(String using, String elementName, Float customAIThreshold)
{
return this.findElement(By.className(using), elementName, customAIThreshold);
}
/**
* Attempts to find an element by class name.
*
* @param using The class name of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByClassName(String using)
{
return findElementByClassName(using, null, null);
}
public WebElement findElementByClassName(String using, Float customAIThreshold)
{
return findElementByClassName(using, null, customAIThreshold);
}
/**
* Attempts to find all elements with the matching class name.
*
* @param using The class name of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByClassName(String using)
{
return driver.findElements(By.className(using));
}
/**
* Attempts to find an element by css selector.
*
* @param using The css selector of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByCssSelector(String using, String elementName)
{
return this.findElement(By.cssSelector(using), elementName);
}
public WebElement findElementByCssSelector(String using, String elementName, Float customAIThreshold)
{
return this.findElement(By.cssSelector(using), elementName, customAIThreshold);
}
/**
* Attempts to find an element by css selector.
*
* @param using The css selector of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByCssSelector(String using)
{
return findElementByCssSelector(using, null, null);
}
public WebElement findElementByCssSelector(String using, Float customAIThreshold)
{
return findElementByCssSelector(using, null, customAIThreshold);
}
/**
* Attempts to find all elements with the matching css selector.
*
* @param using The css selector of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByCssSelector(String using)
{
return driver.findElements(By.cssSelector(using));
}
/**
* Attempts to find an element by id.
*
* @param using The id of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementById(String using, String elementName)
{
return findElement(By.id(using), elementName);
}
public WebElement findElementById(String using, String elementName, Float customAIThreshold)
{
return findElement(By.id(using), elementName, customAIThreshold);
}
/**
* Attempts to find an element by id.
*
* @param using The id of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementById(String using)
{
return findElementById(using, null, null);
}
public WebElement findElementById(String using, Float customAIThreshold)
{
return findElementById(using, null, customAIThreshold);
}
/**
* Attempts to find all elements with the matching id.
*
* @param using The id of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsById(String using)
{
return driver.findElements(By.id(using));
}
/**
* Attempts to find an element by link text.
*
* @param using The link text of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByLinkText(String using, String elementName)
{
return findElement(By.linkText(using), elementName);
}
public WebElement findElementByLinkText(String using, String elementName, Float customAIThreshold)
{
return findElement(By.linkText(using), elementName, customAIThreshold);
}
/**
* Attempts to find an element by link text.
*
* @param using The link text of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByLinkText(String using)
{
return findElementByLinkText(using, null, null);
}
public WebElement findElementByLinkText(String using, Float customAIThreshold)
{
return findElementByLinkText(using, null, customAIThreshold);
}
/**
* Attempts to find all elements with the matching link text.
*
* @param using The link text of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByLinkText(String using)
{
return driver.findElements(By.linkText(using));
}
/**
* Attempts to find an element by name.
*
* @param using The name of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByName(String using, String elementName)
{
return findElement(By.name(using), elementName);
}
public WebElement findElementByName(String using, String elementName, Float customAIThreshold)
{
return findElement(By.name(using), elementName, customAIThreshold);
}
/**
* Attempts to find an element by name.
*
* @param using The name of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByName(String using)
{
return findElementByName(using, null, null);
}
public WebElement findElementByName(String using, Float customAIThreshold)
{
return findElementByName(using, null, customAIThreshold);
}
/**
* Attempts to find all elements with the matching name.
*
* @param using The name of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByName(String using)
{
return driver.findElements(By.name(using));
}
/**
* Attempts to find an element by partial link text.
*
* @param using The partial link text of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByPartialLinkText(String using, String elementName)
{
return findElement(By.partialLinkText(using), elementName);
}
public WebElement findElementByPartialLinkText(String using, String elementName, Float customAIThreshold)
{
return findElement(By.partialLinkText(using), elementName, customAIThreshold);
}
public WebElement findElementByPartialLinkText(String using, Float customAIThreshold)
{
return findElement(By.partialLinkText(using), null, customAIThreshold);
}
/**
* Attempts to find an element by partial link text.
*
* @param using The partial link text of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByPartialLinkText(String using)
{
return findElementByPartialLinkText(using, null, null);
}
/**
* Attempts to find all elements with the matching partial link text.
*
* @param using The partial link text of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByPartialLinkText(String using)
{
return driver.findElements(By.partialLinkText(using));
}
/**
* Attempts to find an element by tag name.
*
* @param using The tag name of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByTagName(String using, String elementName)
{
return findElement(By.tagName(using), elementName);
}
public WebElement findElementByTagName(String using, String elementName, Float customAIThreshold) {
return findElement(By.tagName(using), elementName, customAIThreshold);
}
/**
* Attempts to find an element by tag name.
*
* @param using The tag name of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByTagName(String using)
{
return findElementByTagName(using, null, null);
}
public WebElement findElementByTagName(String using, Float customAIThreshold)
{
return findElementByTagName(using, null, customAIThreshold);
}
/**
* Attempts to find all elements with the matching tag name.
*
* @param using The tag name of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByTagName(String using)
{
return driver.findElements(By.tagName(using));
}
/**
* Attempts to find an element by xpath.
*
* @param using The xpath of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByXPath(String using, String elementName)
{
return findElement(By.xpath(using), elementName);
}
public WebElement findElementByXPath(String using, String elementName, Float customAiThreshold)
{
return findElement(By.xpath(using), elementName, customAiThreshold);
}
/**
* Attempts to find an element by xpath.
*
* @param using The xpath of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByXPath(String using)
{
return findElementByXPath(using, null, null);
}
public WebElement findElementByXPath(String using, Float customAiThreshold)
{
return findElementByXPath(using, null, customAiThreshold);
}
/**
* Attempts to find all elements with the matching xpath.
*
* @param using The xpath of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByXPath(String using)
{
return driver.findElements(By.xpath(using));
}
/**
* Finds an element by {@code elementName}. Please use {@link #findElementByElementName(String)} instead.
*
* @param elementName The label name of the element to be classified.
* @return An element associated with {@code elementName}. Throws NoSuchElementException otherwise.
*/
public WebElement findByElementName(String elementName)
{
return findElementByElementName(elementName);
}
/**
* Finds an element by {@code elementName}.
*
* @param elementName The label name of the element to be classified.
* @return An element associated with {@code elementName}. Throws NoSuchElementException otherwise.
*/
public WebElement findElementByElementName(String elementName, Float customAiThreshold)
{
for(int i = 0; i < classifyMaxRetries; i++) {
ClassifyResult result = classify(elementName, customAiThreshold);
if (result.e != null) {
return result.e;
} else {
if(i == classifyMaxRetries - 1) {
throw new NoSuchElementException(result.msg);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
public WebElement findElementByElementName(String elementName) {
return findElementByElementName(elementName, null);
}
/**
* Finds an elements by {@code elementName}. Uses visual AI to find the element.
*
* @param elementName The label name of the element to be classified.
* @return An element associated with {@code elementName}. Throws NoSuchElementException otherwise.
*/
public WebElement findByAI(String elementName)
{
return findElementByElementName(elementName);
}
public WebElement findByAI(String elementName, Float customAiThreshold)
{
return findElementByElementName(elementName, customAiThreshold);
}
private String getScreenshotHash(String screenshotBase64) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5sum = md.digest(screenshotBase64.getBytes());
String output = String.format("%032X", new BigInteger(1, md5sum));
return output.toLowerCase();
} catch (Throwable e) {
return "";
}
}
private JsonObject checkScreenshotExists(String screenshotUUID, String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot_uuid", screenshotUUID);
payload.add("stack_trace", Utils.collectStackTrace());
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "exists_screenshot", payload));
return res;
} catch (Throwable e) {
log.debug("Error checking if screenshot exists");
e.printStackTrace();
return null;
}
}
private JsonObject uploadScreenshot(String screenshotBase64,String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "upload_screenshot", payload));
return res;
} catch (Throwable e) {
log.debug("Error uploading screenshot");
e.printStackTrace();
return null;
}
}
private JsonObject uploadTCScreenshot(String screenshotBase64, String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
payload.addProperty("is_interactive", true);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "upload_screenshot", payload));
return res;
} catch (Throwable e) {
log.debug("Error uploading test case screenshot");
e.printStackTrace();
return null;
}
}
public void scrollToElement(WebElement element, Boolean scrollUp) {
if(scrollUp) {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(false);", element);
} else {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
}
}
public void scrollPage(int amount) {
((JavascriptExecutor) driver).executeScript("window.scrollBy(0, " + amount + ")");
}
private String uploadScreenshotIfNecessary(String elementName, WebElement element) {
Boolean isElementFrozen = checkIfFrozen(elementName);
if (isElementFrozen) {
return null;
} else {
String screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
String screenshotUUID = getScreenshotHash(screenshotBase64);
refScreenshotUUID = null;
pageOffset = 0f;
if (element != null) {
pageOffset = getPageOffset();
Boolean needsToScroll = (element.getRect().getY() > (windowSize.getHeight() + pageOffset)) || (element.getRect().getY() < pageOffset);
if(needsToScroll) {
previousPageOffset = pageOffset;
refScreenshotUUID = screenshotUUID;
scrollToElement(element, element.getRect().getY() < pageOffset);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
screenshotUUID = getScreenshotHash(screenshotBase64);
pageOffset = getPageOffset();
scrollPage((int) (previousPageOffset - pageOffset));
}
}
JsonObject screenshotExistsResponse = checkScreenshotExists(screenshotUUID, elementName);
if (screenshotExistsResponse != null && screenshotExistsResponse.get("exists_screenshot").getAsBoolean()) {
return screenshotUUID;
} else {
JsonObject uploadScreenshotResponse = uploadScreenshot(screenshotBase64, elementName);
if (uploadScreenshotResponse != null) {
if (uploadScreenshotResponse.get("success").getAsBoolean()) {
return uploadScreenshotResponse.get("screenshot_uuid").getAsString();
} else {
log.info("Error uploading screenshot");
return screenshotUUID;
}
} else {
log.info("Error uploading screenshot");
return screenshotUUID;
}
}
}
}
private Boolean checkIfFrozen(String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "check_frozen", payload));
return res.get("is_frozen").getAsBoolean();
} catch (Throwable e) {
log.debug("Error checking if element is frozen");
e.printStackTrace();
return true;
}
}
/**
* Shared {@code findElementBy} functionality. This serves as the base logic for most find by methods exposed to the end user.
*
* @param using The search term to use when looking for an element.
* @param elementName The label name of the element to be classified. This is what the element will be stored under in the dev-tools.ai db.
* @param shortcode The short identifier for the type of lookup being performed. This will be used to aut-generate an {@code elementName} if the user did not specify one.
* @param fn The selenium function to call with {@code using}, which will be used to fetch what selenium thinks is the target element.
* @return The SmartDriverElement
*/
private WebElement findElementByGeneric(String using, String elementName, String shortcode, Function<String, WebElement> fn)
{
if (elementName == null) {
elementName = String.format("element_name_by_%s_%s", shortcode, using.replace('.', '_'));
}
try
{
WebElement driverElement = fn.apply(using);
if (driverElement != null)
{
String key = uploadScreenshotIfNecessary(elementName, driverElement);
if (key != null) {
updateElement(driverElement, key, elementName, true);
}
}
return driverElement;
}
catch (Throwable x)
{
log.info(MessageFormatter.format("Element '{}' was not found by Selenium, trying with Smartdriver...", elementName).getMessage());
for(int i = 0; i < classifyMaxRetries; i++) {
ClassifyResult result = classify(elementName);
if (result.e != null) {
return result.e;
} else {
if(i == classifyMaxRetries - 1) {
log.error(result.msg);
}
}
}
log.error(MessageFormatter.format("Smartdriver was also unable to find the element with name '{}'", elementName).getMessage());
throw x;
}
}
/**
* Updates the entry for an element as it is known to the dev-tools.ai servers.
*
* @param elem The element to update
* @param screenshotUUID The key associated with this element
* @param elementName The name associated with this element
* @param trainIfNecessary Set {@code true} if the model on the server should also be trained with this element.
*/
protected void updateElement(WebElement elem, String screenshotUUID, String elementName, boolean trainIfNecessary)
{
Rectangle rect = elem.getRect();
JsonObject payload = new JsonObject();
payload.addProperty("screenshot_uuid", screenshotUUID);
payload.addProperty("retrain", trainIfNecessary);
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("x", rect.x * multiplier);
payload.addProperty("y", rect.y * multiplier);
payload.addProperty("width", rect.width * multiplier);
payload.addProperty("height", rect.height * multiplier);
payload.addProperty("multiplier", multiplier);
payload.addProperty("test_case_name", testCaseName);
payload.addProperty("page_offset", this.pageOffset * this.multiplier);
payload.addProperty("ref_screenshot_uuid", this.refScreenshotUUID);
try {
JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "add_action_info", payload));
} catch (Throwable e) {
log.debug("Error updating element");
e.printStackTrace();
}
}
private CollectionUtils.Tuple<JsonObject, Boolean> getTCBox(String elementName, String eventUUID, Float customAiThreshold) {
JsonObject stackTrace = Utils.collectStackTrace();
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot_uuid", lastTestCaseScreenshotUUID);
payload.addProperty("run_classifier", useClassifierDuringCreation);
payload.addProperty("event_id", eventUUID);
payload.addProperty("custom_ai_threshold", customAiThreshold);
payload.add("stack_trace", stackTrace);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "testcase/get_action_info", payload));
Boolean needsReload = res.get("needs_reload").getAsBoolean();
return new CollectionUtils.Tuple<>(res, needsReload);
} catch (Throwable e) {
log.debug("Error getting TC box");
e.printStackTrace();
return new CollectionUtils.Tuple<>(null, false);
}
}
private void openBrowser(String url) {
try {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("mac")) {
Runtime.getRuntime().exec("open " + url);
} else if (os.contains("windows")) {
Desktop.getDesktop().browse(new URI(url));
} else {
log.info(MessageFormatter.format("Please open the following URL in your browser: {}", url).getMessage());
}
} catch (Throwable e) {
log.info(MessageFormatter.format("Please open the following URL in your browser: {}", url).getMessage());
}
}
/**
* Perform additional classification on an element by querying the dev-tools.ai server.
*
* @param elementName The name of the element to run classification on.
* @return The result of the classification.
*/
protected ClassifyResult classify(String elementName, Float customAiThreshold)
{
JsonObject stackTrace = Utils.collectStackTrace();
if(testCaseCreationMode) {
String screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
JsonObject res = uploadTCScreenshot(screenshotBase64, elementName);
if (res.get("success").getAsBoolean()) {
lastTestCaseScreenshotUUID = res.get("screenshot_uuid").getAsString();
CollectionUtils.Tuple<JsonObject, Boolean> boxResponseTp = getTCBox(elementName, null, customAiThreshold);
JsonObject boxResponse = boxResponseTp.k;
Boolean needsReload = boxResponseTp.v;
if (boxResponse != null && boxResponse.get("success").getAsBoolean() && boxResponse.get("predicted_element") != JsonNull.INSTANCE) {
return new ClassifyResult(new SmartDriverElement(boxResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()), lastTestCaseScreenshotUUID, boxResponse);
} else {
// label_url = self.url + '/testcase/label?test_case_name=' + urllib.parse.quote(self.test_case_uuid)
// generate a uuid
String eventUUID = UUID.randomUUID().toString();
String labelUrl = serverURL + "/testcase/label?test_case_name=" + URLEncoder.encode(testCaseName) + "&event_id=" + eventUUID + "&api_key=" + apiKey;;
openBrowser(labelUrl);
while (true) {
boxResponseTp = getTCBox(elementName, eventUUID, customAiThreshold);
boxResponse = boxResponseTp.k;
needsReload = boxResponseTp.v;
if (boxResponse != null && boxResponse.get("success").getAsBoolean() && boxResponse.get("predicted_element") != JsonNull.INSTANCE) {
return new ClassifyResult(new SmartDriverElement(boxResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()), lastTestCaseScreenshotUUID, boxResponse);
}
if (needsReload) {
screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
lastTestCaseScreenshotUUID = getScreenshotHash(screenshotBase64);
uploadTCScreenshot(screenshotBase64, elementName);
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} else {
log.info("Failed to upload test case screenshot");
log.info(res.get("message").getAsString());
return new ClassifyResult(null, lastTestCaseScreenshotUUID, res.get("message").getAsString(), res);
}
} else {
String pageSource = "", msg = "Smartdriver driver exception", key = null;
try {
String screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
String screenshotUUID = getScreenshotHash(screenshotBase64);
JsonObject screenshotExistsResponse = checkScreenshotExists(screenshotUUID, elementName);
if (screenshotExistsResponse != null && screenshotExistsResponse.get("success").getAsBoolean() && screenshotExistsResponse.get("predicted_element") != JsonNull.INSTANCE) {
msg = screenshotExistsResponse.get("message").getAsString();
log.info(msg);
float currentOffset = getPageOffset();
float bottomOffset = currentOffset + windowSize.height;
float realOffset = (float) (screenshotExistsResponse.get("page_offset").getAsFloat() / multiplier);
if (realOffset > bottomOffset || realOffset < currentOffset) {
int scrollOffset = (int) (realOffset - currentOffset);
// Scroll
scrollPage((int) scrollOffset);
Thread.sleep(1000);
screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
screenshotUUID = getScreenshotHash(screenshotBase64);
screenshotExistsResponse = checkScreenshotExists(screenshotUUID, elementName);
}
if (screenshotExistsResponse != null && screenshotExistsResponse.get("success").getAsBoolean() && screenshotExistsResponse.get("predicted_element") != JsonNull.INSTANCE) {
return new ClassifyResult(new SmartDriverElement(screenshotExistsResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()), null, screenshotExistsResponse);
}
}
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
payload.add("stack_trace", stackTrace);
payload.addProperty("custom_ai_threshold", customAiThreshold);
JsonObject classifyResponse = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "detect", payload));
if (!classifyResponse.get("success").getAsBoolean()) {
classifyResponse = classifyFullScreen(elementName, screenshotBase64, customAiThreshold);
if (!classifyResponse.get("success").getAsBoolean()) {
msg = classifyResponse.get("message").getAsString().replace(prodUrl, serverURL.toString());
log.info(msg);
return new ClassifyResult(null, null, classifyResponse.get("message").getAsString(), classifyResponse);
}
}
msg = classifyResponse.get("message").getAsString().replace(prodUrl, serverURL.toString());
log.info(msg);
try {
return new ClassifyResult(new SmartDriverElement(classifyResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()),
classifyResponse.get("screenshot_uuid").getAsString(), classifyResponse);
} catch (Throwable e) {
log.error("Error creating SmartDriverElement from response");
e.printStackTrace();
return new ClassifyResult(null, key, msg, classifyResponse);
}
} catch (Throwable e) {
e.printStackTrace();
}
log.warn(msg);
return new ClassifyResult(null, key, msg, null);
}
}
protected ClassifyResult classify(String elementName) {
return classify(elementName, null);
}
private float getPageOffset(){
Object res = driver.executeScript("return window.pageYOffset;");
if (res instanceof Number) {
return ((Number) res).floatValue();
} else {
return 0;
}
}
JsonObject classifyFullScreen(String elementName, String screenshotBase64) {
return classifyFullScreen(elementName, screenshotBase64, null);
}
JsonObject classifyFullScreen(String elementName, String screenshotBase64, Float customAiThreshold) {
int lastOffset = -1;
int offset = 1;
int windowHeight = windowSize.height;
scrollPage(-100000);
JsonObject r = new JsonObject();
r.addProperty("success", false);
JsonObject stackTrace = Utils.collectStackTrace();
while(offset > lastOffset) {
lastOffset = offset;
screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
payload.addProperty("custom_ai_threshold", customAiThreshold);
payload.add("stack_trace", stackTrace);
try {
r = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "detect", payload));
if (r.get("success").getAsBoolean()) {
return r;
}
} catch (Throwable e) {
log.error("Error creating SmartDriverElement from response");
e.printStackTrace();
return r;
}
scrollPage((int) windowHeight);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
offset = (int) getPageOffset();
}
return r;
}
/**
* Simple container for encapsulating results of calls to {@code classify()}.
*
*/
private static class ClassifyResult
{
/**
* The SmartDriverElement created by the call to classify
*/
public SmartDriverElement e;
/**
* The key returned by the call to classify
*/
public String key;
/**
* The message associated with this result
*/
public String msg;
public JsonObject classifyResponse;
/**
* Constructor, creates a new ClassifyResult.
*
* @param e The SmartDriverElement to to use
* @param key The key to use
* @param msg The message to associate with this result
*/
ClassifyResult(SmartDriverElement e, String key, String msg, JsonObject classifyResponse)
{
this.e = e;
this.key = key;
this.msg = msg;
this.classifyResponse = classifyResponse;
}
/**
* Constructor, creates a new ClassifyResult, where the {@code msg} is set to the empty String by default.
*
* @param e
* @param key
*/
ClassifyResult(SmartDriverElement e, String key, JsonObject classifyResponse)
{
this(e, key, "", classifyResponse);
}
}
@Override
public void close() {
driver.close();
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/selenium/SmartDriverElement.java
|
package ai.devtools.selenium;
import ai.devtools.utils.JsonUtils;
import ai.devtools.utils.MatchUtils;
import com.google.gson.JsonObject;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.RemoteWebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An enhanced RemoteWebElement which uses the results of the dev-tools.ai classifier for improved accuracy.
*
*/
public class SmartDriverElement extends RemoteWebElement
{
/**
* The logger for this class
*/
private static Logger log = LoggerFactory.getLogger(SmartDriverElement.class);
/**
* The webdriver the user is using. We wrap this for when the user calls methods that interact with selenium.
*/
private RemoteWebDriver driver;
/**
* The underlying {@code WebElement} used for performing actions in the browser.
*/
private WebElement realElement;
/**
* The text in this element, as determined by dev-tools.ai's classifier
*/
private String text;
/**
* The size of this element, in pixels
*/
private Dimension size;
/**
* The location of this element, in pixels (offset from the upper left corner of the screen)
*/
private Point location;
/**
* The rectangle that can be drawn around this element. Basically combines size and location.
*/
private Rectangle rectangle;
/**
* The tag name of this element, as determined by dev-tools.ai's classifier
*/
private String tagName;
SmartDriverElement(JsonObject elem, SmartDriver driver) {
this(elem, driver, 0);
}
/**
* Constructor, creates a new SmartDriverElement
*
* @param elem The element data returned by the FD API, as JSON
* @param driver The {@code SmartDriver} to associate with this {@code SmartDriverElement}.
*/
SmartDriverElement(JsonObject elem, SmartDriver driver, float page_offset)
{
log.debug("Creating new SmartDriverElement w/ {}", elem);
this.driver = driver.driver;
int pageY = elem.get("y").getAsInt();
elem.remove("y");
elem.addProperty("y", pageY + page_offset * driver.multiplier);
this.realElement = MatchUtils.matchBoundingBoxToSeleniumElement(elem, driver);
text = JsonUtils.stringFromJson(elem, "text");
size = new Dimension(JsonUtils.intFromJson(elem, "width") / Math.max((int) driver.multiplier, 1), JsonUtils.intFromJson(elem, "height") / Math.max((int) driver.multiplier, 1));
location = new Point(JsonUtils.intFromJson(elem, "x") / Math.max((int) driver.multiplier, 1), JsonUtils.intFromJson(elem, "y") / Math.max((int) driver.multiplier, 1));
// this.property = property //TODO: not referenced/implemented on python side??
rectangle = new Rectangle(location, size);
tagName = JsonUtils.stringFromJson(elem, "class");
}
public String toString()
{
return "SmartDriverElement: " + text;
}
@Override
public String getText()
{
return realElement.getText();
}
@Override
public Dimension getSize()
{
return size;
}
@Override
public Point getLocation()
{
return location;
}
@Override
public Rectangle getRect()
{
return rectangle;
}
@Override
public String getTagName()
{
return realElement.getTagName();
}
@Override
public void clear()
{
realElement.clear();
}
@Override
public WebElement findElement(By by)
{
return driver.findElement(by);
}
@Override
public List<WebElement> findElements(By by)
{
return driver.findElements(by);
}
@Override
public String getAttribute(String name)
{
return realElement.getAttribute(name);
}
@Override
public String getCssValue(String propertyName)
{
return realElement.getCssValue(propertyName);
}
@Override
public boolean isDisplayed()
{
return realElement.isDisplayed();
}
@Override
public boolean isEnabled()
{
return realElement.isEnabled();
}
@Override
public boolean isSelected()
{
return realElement.isSelected();
}
@Override
public void click()
{
realElement.click();
}
@Override
public void sendKeys(CharSequence... keysToSend)
{
realElement.sendKeys(keysToSend);
}
@Override
public void submit()
{
realElement.submit();
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/utils/CollectionUtils.java
|
package ai.devtools.utils;
import com.google.gson.JsonObject;
import java.util.HashMap;
public class CollectionUtils
{
/**
* Builds a new {@code JsonObject} from the list of Objects. Pass in values such that {@code [ k1, v1, k2, v2, k3, v3... ]}.
*
* @param ol The {@code Object}s to use
* @return A {@code JsonObject} derived from the values in {@code ol}
*/
public static JsonObject keyValuesToJO(Object... ol)
{
JsonObject jo = new JsonObject();
for (int i = 0; i < ol.length; i += 2)
{
String k = (String) ol[i];
Object v = ol[i + 1];
if (v instanceof String)
jo.addProperty(k, (String) v);
else if (v instanceof Number)
jo.addProperty(k, (Number) v);
else if (v instanceof Boolean)
jo.addProperty(k, (Boolean) v);
else if (v instanceof Character)
jo.addProperty(k, (Character) v);
else if (v instanceof JsonObject)
jo.add(k, (JsonObject) v);
else
throw new IllegalArgumentException(String.format("'%s' is not an acceptable type for JSON!", v));
}
return jo;
}
/**
* Simple Tuple implementation. A Tuple is an immutable two-pair of values. It may consist of any two Objects, which may or may not be in of the same type.
*
* @param <K> The type of Object allowed for the first Object in the tuple.
* @param <V> The type of Object allowed for the second Object in the tuple.
*/
public static class Tuple<K, V>
{
/**
* The k value of the tuple
*/
public final K k;
/**
* The v value of the tuple
*/
public final V v;
/**
* Constructor, creates a new Tuple from the specified values.
*
* @param k The first entry in the Tuple.
* @param v The second entry in the Tuple.
*/
public Tuple(K k, V v)
{
this.k = k;
this.v = v;
}
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/utils/JsonUtils.java
|
package ai.devtools.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.Response;
/**
* Shared utility methods for common tasks
*/
public class JsonUtils
{
/**
* The logger for this class
*/
private static Logger log = LoggerFactory.getLogger(JsonUtils.class);
/**
* Convenience method, extract the body of a {@code Response} as a {@code JsonObject}.
*
* @param r The Response object to use
* @return The body of {@code r} as a {@code JsonObject}.
*/
public static JsonObject responseAsJson(Response r)
{
try
{
String body = r.body().string();
log.debug("Status: {} ----- Body: {}", r.code(), body);
return JsonParser.parseString(body).getAsJsonObject();
}
catch (Throwable e)
{
e.printStackTrace();
return null;
}
}
/**
* Convenience method, extract a String value associated with the specified key on a JsonObject.
*
* @param jo The JsonObject to extract a String from
* @param key The key associated with the value to extract
* @return The value associated with {@code key}, or the empty String if {@code key} was not in {@code jo}.
*/
public static String stringFromJson(JsonObject jo, String key)
{
return jo.has(key) ? jo.get(key).getAsString() : "";
}
/**
* Convenience method, extract a double value associated with the specified key on a JsonObject.
*
* @param jo The JsonObject to extract a double from
* @param key The key associated with the value to extract
* @return The value associated with {@code key}, or 0.0 if {@code key} was not in {@code jo}.
*/
public static double doubleFromJson(JsonObject jo, String key)
{
return jo.has(key) ? jo.get(key).getAsDouble() : 0;
}
/**
* Convenience method, extract an int value associated with the specified key on a JsonObject.
*
* @param jo The JsonObject to extract an int from
* @param key The key associated with the value to extract
* @return The value associated with {@code key}, or 0 if {@code key} was not in {@code jo}.
*/
public static int intFromJson(JsonObject jo, String key)
{
return jo.has(key) ? jo.get(key).getAsInt() : 0;
}
/**
* Convenience method, extract a boolean value associated with the specified key on a JsonObject.
*
* @param jo The JsonObject to extract a boolean from
* @param key The key associated with the value to extract
* @return The value associated with {@code key}, or false if {@code key} was not in {@code jo}.
*/
public static boolean booleanFromJson(JsonObject jo, String key)
{
return jo.has(key) ? jo.get(key).getAsBoolean() : false;
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/utils/LocalClassifyUtils.java
|
package ai.devtools.utils;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.io.IOException;
public class LocalClassifyUtils {
public void match() throws IOException {
// Load the image and the template
String inputImageFilename = System.getenv("IMG_INP");
String templateImageFilename = System.getenv("IMG_TPL");
BufferedImage image = ImageIO.read(new File(inputImageFilename));
BufferedImage template = ImageIO.read(new File(templateImageFilename));
// Convert the images to grayscale
BufferedImage grayImage = toGrayscale(image);
BufferedImage grayTemplate = toGrayscale(template);
// Find the best match
int bestX = 0, bestY = 0;
double bestValue = Double.NEGATIVE_INFINITY;
for (int y = 0; y <= grayImage.getHeight() - grayTemplate.getHeight(); y++) {
for (int x = 0; x <= grayImage.getWidth() - grayTemplate.getWidth(); x++) {
double value = templateMatching(grayImage, grayTemplate, x, y);
if (value > bestValue) {
bestX = x;
bestY = y;
bestValue = value;
}
}
}
System.out.println("Match found at " + bestX + ", " + bestY);
}
private static BufferedImage toGrayscale(BufferedImage image) {
BufferedImage grayImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = grayImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return grayImage;
}
private static double templateMatching(BufferedImage image, BufferedImage template, int x, int y) {
double sum = 0.0;
for (int j = 0; j < template.getHeight(); j++) {
for (int i = 0; i < template.getWidth(); i++) {
int imagePixel = image.getRGB(x + i, y + j) & 0xFF;
int templatePixel = template.getRGB(i, j) & 0xFF;
sum += Math.pow(imagePixel - templatePixel, 2);
}
}
return -sum / (template.getWidth() * template.getHeight());
}
public void testTemplateMatch() {
nu.pattern.OpenCV.loadShared();
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
String inputImageFilename = System.getenv("IMG_INP");
String templateImageFilename = System.getenv("IMG_TPL");
Mat inputImage = Imgcodecs.imread(inputImageFilename);
Mat templateImage = Imgcodecs.imread(templateImageFilename);
// Create the result matrix
Mat result = new Mat();
// Perform the template matching operation
Imgproc.matchTemplate(inputImage, templateImage, result, Imgproc.TM_CCOEFF);
// Find the maximum value in the result matrix
Core.MinMaxLocResult mmr = Core.minMaxLoc(result);
// Get the location of the maximum value
Point matchLoc = mmr.maxLoc;
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/utils/MatchUtils.java
|
package ai.devtools.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import ai.devtools.selenium.SmartDriver;
import org.openqa.selenium.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonObject;
import ai.devtools.utils.CollectionUtils.Tuple;
/**
* Static methods for matching bounding boxes to underlying Selenium elements.
*/
public class MatchUtils {
/**
* The logger for this class
*/
private static Logger log = LoggerFactory.getLogger(MatchUtils.class);
public static WebElement matchBoundingBoxToSeleniumElementJS(JsonObject boundingBox, SmartDriver driver) {
HashMap<String, Double> newBox = new HashMap<>();
newBox.put("x", boundingBox.get("x").getAsDouble() / driver.multiplier);
newBox.put("y", boundingBox.get("y").getAsDouble() / driver.multiplier);
newBox.put("width", boundingBox.get("width").getAsDouble() / driver.multiplier);
newBox.put("height", boundingBox.get("height").getAsDouble() / driver.multiplier);
Double centerX = newBox.get("x") + newBox.get("width") / 2;
Double centerY = newBox.get("y") + newBox.get("height") / 2;
WebElement element = (WebElement)((JavascriptExecutor) driver).executeScript(
"return document.elementFromPoint(arguments[0], arguments[1])",
centerX, centerY);
return element;
}
/**
* Matches a bounding box returned by the dev-tools.ai API to a selenium WebElement on the current page.
*
* @param boundingBox The json representing the element returned by the dev-tools.ai API.
* @param driver The {@code SmartDriver} to use
* @return The best-matching, underlying {@code WebElement} which best fits the parameters specified by {@code boudingBox}
*/
public static WebElement matchBoundingBoxToSeleniumElement(JsonObject boundingBox, SmartDriver driver)
{
if(driver.UseJSChopper) {
WebElement res = matchBoundingBoxToSeleniumElementJS(boundingBox, driver);
if(res != null) {
return res;
}
}
HashMap<String, Double> newBox = new HashMap<>();
newBox.put("x", boundingBox.get("x").getAsDouble() / driver.multiplier);
newBox.put("y", boundingBox.get("y").getAsDouble() / driver.multiplier);
newBox.put("width", boundingBox.get("width").getAsDouble() / driver.multiplier);
newBox.put("height", boundingBox.get("height").getAsDouble() / driver.multiplier);
List<WebElement> elements = driver.driver.findElements(By.xpath("//*"));
List<Double> iouScores = new ArrayList<>();
for (WebElement e : elements)
try
{
iouScores.add(iouBoxes(newBox, e.getRect()));
}
catch (StaleElementReferenceException x)
{
log.debug("Stale reference to element '{}', setting score of 0", e);
iouScores.add(0.0);
}
List<Tuple<Double, WebElement>> composite = new ArrayList<>();
for (int i = 0; i < iouScores.size(); i++)
composite.add(new Tuple<>(iouScores.get(i), elements.get(i)));
Collections.sort(composite, (o1, o2) -> o2.k.compareTo(o1.k)); // sort the composite values in reverse (descending) order
composite = composite.stream().filter(x -> x.k > 0).filter(x -> centerHit(newBox, x.v.getRect())).collect(Collectors.toList());
if (composite.size() == 0)
throw new NoSuchElementException("Could not find any web element under the center of the bounding box");
for (Tuple<Double, WebElement> t : composite)
if (t.v.getTagName().equals("input") || t.v.getTagName().equals(("button")) && t.k > composite.get(0).k * 0.9)
return t.v;
return composite.get(0).v;
}
/**
* Calculate the IOU score of two rectangles. This is derived from the overlap and areas of both rectangles.
*
* @param box1 The first box The first rectangle to check (the json returned from the dev-tools.ai API)
* @param box2 The second box The second rectangle to check (the Rectangle from the selenium WebElement)
* @return The IOU score of the two rectangles. Higher score means relative to other scores (obtained from comparisons between other pairs of rectangles) means better match.
*/
private static double iouBoxes(Map<String, Double> box1, Rectangle box2)
{
return iou(box1.get("x"), box1.get("y"), box1.get("width"), box1.get("height"), (double) box2.x, (double) box2.y, (double) box2.width, (double) box2.height);
}
/**
* Calculate the IOU score of two rectangles. This is derived from the overlap and areas of both rectangles.
*
* @param x The x coordinate of the first box (upper left corner)
* @param y The y coordinate of the first box (upper left corner)
* @param w The width of the first box
* @param h The height of the first box
* @param xx The x coordinate of the second box (upper left corner)
* @param yy The y coordinate of the second box (upper left corner)
* @param ww The width of the second box
* @param hh The height of the second box
* @return The IOU value of both boxes.
*/
private static double iou(double x, double y, double w, double h, double xx, double yy, double ww, double hh)
{
double overlap = areaOverlap(x, y, w, h, xx, yy, ww, hh);
return overlap / (area(w, h) + area(ww, hh) - overlap);
}
/**
* Determines the amount of area overlap between two rectangles
*
* @param x The x coordinate of the first box (upper left corner)
* @param y The y coordinate of the first box (upper left corner)
* @param w The width of the first box
* @param h The height of the first box
* @param xx The x coordinate of the second box (upper left corner)
* @param yy The y coordinate of the second box (upper left corner)
* @param ww The width of the second box
* @param hh The height of the second box
* @return The amount of overlap, in square pixels.
*/
private static double areaOverlap(double x, double y, double w, double h, double xx, double yy, double ww, double hh)
{
double dx = Math.min(x + w, xx + ww) - Math.max(x, xx), dy = Math.min(y + h, yy + hh) - Math.max(y, yy);
return dx >= 0 && dy >= 0 ? dx * dy : 0;
}
/**
* Convenience function, calculates the area of a rectangle
*
* @param w The width of the rectangle
* @param h The height of the rectangle
* @return The area of the rectangle
*/
private static double area(double w, double h)
{
return w * h;
}
/**
* Determines if center point of {@code box1} falls within the area of {@code box2}
*
* @param box1 The first rectangle to check (the json returned from the dev-tools.ai API)
* @param box2 The second rectangle to check (the Rectangle from the selenium WebElement)
* @return {@code true} if the center point of {@code box1} falls within the area of {@code box2}
*/
private static boolean centerHit(Map<String, Double> box1, Rectangle box2)
{
double centerX = box1.get("x") + box1.get("width") / 2, centerY = box1.get("y") + box1.get("height") / 2;
return centerX > box2.x && centerX < box2.x + box2.width && centerY > box2.y && centerY < box2.y + box2.height;
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/utils/MatchUtilsAppium.java
|
package ai.devtools.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import ai.devtools.appium.SmartDriver;
import io.appium.java_client.MobileElement;
import org.openqa.selenium.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonObject;
import ai.devtools.utils.CollectionUtils.Tuple;
/**
* Static methods for matching bounding boxes to underlying Selenium elements.
*/
public class MatchUtilsAppium<T extends MobileElement> {
/**
* The logger for this class
*/
private static Logger log = LoggerFactory.getLogger(MatchUtils.class);
/**
* Matches a bounding box returned by the dev-tools.ai API to a selenium T on the current page.
*
* @param boundingBox The json representing the element returned by the dev-tools.ai API.
* @param driver The {@code SmartDriver} to use
* @return The best-matching, underlying {@code T} which best fits the parameters specified by {@code boudingBox}
*/
public T matchBoundingBoxToAppiumElement(JsonObject boundingBox, SmartDriver<T> driver)
{
HashMap<String, Double> newBox = new HashMap<>();
newBox.put("x", boundingBox.get("x").getAsDouble() / driver.multiplier);
newBox.put("y", boundingBox.get("y").getAsDouble() / driver.multiplier);
newBox.put("width", boundingBox.get("width").getAsDouble() / driver.multiplier);
newBox.put("height", boundingBox.get("height").getAsDouble() / driver.multiplier);
List<T> elements = driver.driver.findElements(By.xpath("//*"));
List<Double> iouScores = new ArrayList<>();
for (T e : elements)
try
{
iouScores.add(iouBoxes(newBox, e.getRect()));
}
catch (StaleElementReferenceException x)
{
log.debug("Stale reference to element '{}', setting score of 0", e);
iouScores.add(0.0);
}
List<Tuple<Double, T>> composite = new ArrayList<>();
for (int i = 0; i < iouScores.size(); i++)
composite.add(new Tuple<>(iouScores.get(i), elements.get(i)));
Collections.sort(composite, (o1, o2) -> o2.k.compareTo(o1.k)); // sort the composite values in reverse (descending) order
composite = composite.stream().filter(x -> x.k > 0).filter(x -> centerHit(newBox, x.v.getRect())).collect(Collectors.toList());
String attributeForClasses = "className";
if(driver.isEspresso) {
attributeForClasses = "class";
} else if (driver.isIOS) {
attributeForClasses = "type";
}
ArrayList<String> interactableElements = new ArrayList<>();
interactableElements.add("input");
interactableElements.add("edittext");
interactableElements.add("edit");
interactableElements.add("select");
interactableElements.add("dropdown");
interactableElements.add("button");
interactableElements.add("textfield");
interactableElements.add("textarea");
interactableElements.add("picker");
ArrayList<String> nonInteractableElements = new ArrayList<>();
nonInteractableElements.add("layout");
// We are going to go through thte list in decreasing iOU order, and stop as soon as we find an interactable element
// Since the element names differ from automation to automation (ios, android, uiautomator2, espresso), we have factored
// in the class names that are preferred and we also rule out layout components.
for (Tuple<Double, T> t : composite) {
for(String s : interactableElements) {
if(t.v.getAttribute(attributeForClasses).toLowerCase().contains(s) &&
t.k > composite.get(0).k * 0.6) {
boolean containsNonInteractable = false;
for(String s2 : nonInteractableElements) {
if(t.v.getAttribute(attributeForClasses).toLowerCase().contains(s2)) {
containsNonInteractable = true;
break;
}
}
if(!containsNonInteractable) {
return t.v;
}
}
}
}
if (composite.size() == 0)
throw new NoSuchElementException("Could not find any web element under the center of the bounding box");
return composite.get(0).v;
}
/**
* Calculate the IOU score of two rectangles. This is derived from the overlap and areas of both rectangles.
*
* @param box1 The first box The first rectangle to check (the json returned from the dev-tools.ai API)
* @param box2 The second box The second rectangle to check (the Rectangle from the selenium T)
* @return The IOU score of the two rectangles. Higher score means relative to other scores (obtained from comparisons between other pairs of rectangles) means better match.
*/
private static double iouBoxes(Map<String, Double> box1, Rectangle box2)
{
return iou(box1.get("x"), box1.get("y"), box1.get("width"), box1.get("height"), (double) box2.x, (double) box2.y, (double) box2.width, (double) box2.height);
}
/**
* Calculate the IOU score of two rectangles. This is derived from the overlap and areas of both rectangles.
*
* @param x The x coordinate of the first box (upper left corner)
* @param y The y coordinate of the first box (upper left corner)
* @param w The width of the first box
* @param h The height of the first box
* @param xx The x coordinate of the second box (upper left corner)
* @param yy The y coordinate of the second box (upper left corner)
* @param ww The width of the second box
* @param hh The height of the second box
* @return The IOU value of both boxes.
*/
private static double iou(double x, double y, double w, double h, double xx, double yy, double ww, double hh)
{
double overlap = areaOverlap(x, y, w, h, xx, yy, ww, hh);
return overlap / (area(w, h) + area(ww, hh) - overlap);
}
/**
* Determines the amount of area overlap between two rectangles
*
* @param x The x coordinate of the first box (upper left corner)
* @param y The y coordinate of the first box (upper left corner)
* @param w The width of the first box
* @param h The height of the first box
* @param xx The x coordinate of the second box (upper left corner)
* @param yy The y coordinate of the second box (upper left corner)
* @param ww The width of the second box
* @param hh The height of the second box
* @return The amount of overlap, in square pixels.
*/
private static double areaOverlap(double x, double y, double w, double h, double xx, double yy, double ww, double hh)
{
double dx = Math.min(x + w, xx + ww) - Math.max(x, xx), dy = Math.min(y + h, yy + hh) - Math.max(y, yy);
return dx >= 0 && dy >= 0 ? dx * dy : 0;
}
/**
* Convenience function, calculates the area of a rectangle
*
* @param w The width of the rectangle
* @param h The height of the rectangle
* @return The area of the rectangle
*/
private static double area(double w, double h)
{
return w * h;
}
/**
* Determines if center point of {@code box1} falls within the area of {@code box2}
*
* @param box1 The first rectangle to check (the json returned from the dev-tools.ai API)
* @param box2 The second rectangle to check (the Rectangle from the selenium T)
* @return {@code true} if the center point of {@code box1} falls within the area of {@code box2}
*/
private static boolean centerHit(Map<String, Double> box1, Rectangle box2)
{
double centerX = box1.get("x") + box1.get("width") / 2, centerY = box1.get("y") + box1.get("height") / 2;
return centerX > box2.x && centerX < box2.x + box2.width && centerY > box2.y && centerY < box2.y + box2.height;
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/utils/NetUtils.java
|
package ai.devtools.utils;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.HashMap;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import okhttp3.*;
/**
* Shared network/http-related utilities and functionality
*/
public class NetUtils
{
/**
* The {@code MediaType} representing the json MIME type.
*/
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
/**
* Performs a simple POST to the specified url with the provided client and {@code RequestBody}.
*
* @param client The OkHttp client to use
* @param baseURL The base URL to target
* @param endpoint The endpoint on the baseURL to target.
* @param b The request body to POST.
* @return The response from the server, in the form of a {@code Response} object
* @throws IOException Network error
*/
private static Response basicPOST(OkHttpClient client, HttpUrl baseURL, String endpoint, RequestBody b) throws IOException
{
return client.newCall(new Request.Builder().url(baseURL.newBuilder().addPathSegment(endpoint).build()).post(b).build()).execute();
}
public static JsonObject post(String url, JsonObject json) throws IOException
{
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(Duration.ofSeconds(30)).readTimeout(Duration.ofSeconds(30)).build();
RequestBody payload = new FormBody.Builder().add("json", json.toString()).build();
Request request = new Request.Builder()
.url(url)
.post(payload)
.build();
Call call = client.newCall(request);
try (Response response = client.newCall(request).execute()) {
return new Gson().fromJson(response.body().string(), JsonObject.class);
} catch (IOException e) {
throw e;
}
}
/**
* Performs a simple POST to the specified url with the provided client and json data.
*
* @param client The OkHttp client to use
* @param baseURL The base URL to target
* @param endpoint The endpoint on the baseURL to target.
* @param jo The JsonObject to put in the request body
* @return The response from the server, in the form of a {@code Response} object
* @throws IOException Network error
*/
public static Response basicPOST(OkHttpClient client, HttpUrl baseURL, String endpoint, JsonObject jo) throws IOException
{
return basicPOST(client, baseURL, endpoint, RequestBody.create(jo.toString(), JSON));
}
/**
* Performs a simple form POST to the specified url with the provided client and form data.
*
* @param client The OkHttp client to use
* @param baseURL The base URL to target
* @param endpoint The endpoint on the baseURL to target.
* @param form The form data to POST
* @return The response from the server, in the form of a {@code Response} object
* @throws IOException Network error
*/
public static Response basicPOST(OkHttpClient client, HttpUrl baseURL, String endpoint, HashMap<String, String> form) throws IOException
{
FormBody.Builder fb = new FormBody.Builder();
form.forEach(fb::add);
return basicPOST(client, baseURL, endpoint, fb.build());
}
/**
* Convenience method, creates a new OkHttpBuilder with timeouts configured.
*
* @return A OkHttpClient builder with reasonable timeouts configured.
*/
public static OkHttpClient.Builder basicClient()
{
Duration d = Duration.ofSeconds(60);
return new OkHttpClient.Builder().connectTimeout(d).writeTimeout(d).readTimeout(d).callTimeout(d);
}
/**
* Creates a new {@code OkHttpClient} which ignores expired/invalid ssl certificates. Normally, OkHttp will raise an exception if it encounters bad certificates.
*
* @return A new {@code OkHttpClient} which ignores expired/invalid ssl certificates.
*/
public static OkHttpClient unsafeClient()
{
try
{
TrustManager tl[] = { new TrustAllX509Manager() };
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, tl, new SecureRandom());
return basicClient().sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) tl[0]).hostnameVerifier(new TrustAllHostnameVerifier()).build();
}
catch (Throwable e) // highly unlikely, shut up compiler
{
return null;
}
}
/**
* A dummy {@code HostnameVerifier} which doesn't actually do any hostname checking.
*
* @author Alexander Wu (alec@dev-tools.ai)
*
*/
private static class TrustAllHostnameVerifier implements HostnameVerifier
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
}
/**
* A dummy {@code X509TrustManager} which doesn't actually do any certificate verification.
*
* @author Alexander Wu (alec@dev-tools.ai)
*
*/
private static class TrustAllX509Manager implements 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 new X509Certificate[0];
}
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools/0.1.20/ai/devtools/utils/Utils.java
|
package ai.devtools.utils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.Arrays;
/**
* The {@code Utils} class provide a function for turning strings into Booleans.
*/
public class Utils {
public static Boolean StrToBool(String value) {
ArrayList<String> truthValues = new ArrayList<String>(Arrays.asList("1", "true", "yes"));
if (truthValues.contains(value != null ? value.toLowerCase() : "false")) {
return true;
} else {
return false;
}
}
public static JsonObject collectStackTrace() {
StackTraceElement[] st = Thread.currentThread().getStackTrace();
JsonArray jsStFilenames = new JsonArray();
JsonArray jsStTraces = new JsonArray();
for(int i = 0; i < st.length; i++) {
StackTraceElement ste = st[i];
String filename = ste.getFileName();
if (filename != null) {
JsonArray filenameLinenumber = new JsonArray();
filenameLinenumber.add(filename);
filenameLinenumber.add(ste.getLineNumber());
jsStFilenames.add(filenameLinenumber);
}
jsStTraces.add(ste.toString());
}
JsonObject stackTrace = new JsonObject();
stackTrace.add("filenames", jsStFilenames);
stackTrace.add("traces", jsStTraces);
return stackTrace;
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools/selenium/CollectionUtils.java
|
package ai.devtools.selenium;
import com.google.gson.JsonObject;
final class CollectionUtils
{
/**
* Builds a new {@code JsonObject} from the list of Objects. Pass in values such that {@code [ k1, v1, k2, v2, k3, v3... ]}.
*
* @param ol The {@code Object}s to use
* @return A {@code JsonObject} derived from the values in {@code ol}
*/
public static JsonObject keyValuesToJO(Object... ol)
{
JsonObject jo = new JsonObject();
for (int i = 0; i < ol.length; i += 2)
{
String k = (String) ol[i];
Object v = ol[i + 1];
if (v instanceof String)
jo.addProperty(k, (String) v);
else if (v instanceof Number)
jo.addProperty(k, (Number) v);
else if (v instanceof Boolean)
jo.addProperty(k, (Boolean) v);
else if (v instanceof Character)
jo.addProperty(k, (Character) v);
else
throw new IllegalArgumentException(String.format("'%s' is not an acceptable type for JSON!", v));
}
return jo;
}
/**
* Simple Tuple implementation. A Tuple is an immutable two-pair of values. It may consist of any two Objects, which may or may not be in of the same type.
*
* @param <K> The type of Object allowed for the first Object in the tuple.
* @param <V> The type of Object allowed for the second Object in the tuple.
*/
public static class Tuple<K, V>
{
/**
* The k value of the tuple
*/
public final K k;
/**
* The v value of the tuple
*/
public final V v;
/**
* Constructor, creates a new Tuple from the specified values.
*
* @param k The first entry in the Tuple.
* @param v The second entry in the Tuple.
*/
public Tuple(K k, V v)
{
this.k = k;
this.v = v;
}
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools/selenium/JsonUtils.java
|
package ai.devtools.selenium;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.Response;
/**
* Shared utility methods for common tasks
*/
final class JsonUtils
{
/**
* The logger for this class
*/
private static Logger log = LoggerFactory.getLogger(JsonUtils.class);
/**
* Convenience method, extract the body of a {@code Response} as a {@code JsonObject}.
*
* @param r The Response object to use
* @return The body of {@code r} as a {@code JsonObject}.
*/
public static JsonObject responseAsJson(Response r)
{
try
{
String body = r.body().string();
log.debug("Status: {} ----- Body: {}", r.code(), body);
return JsonParser.parseString(body).getAsJsonObject();
}
catch (Throwable e)
{
e.printStackTrace();
return null;
}
}
/**
* Convenience method, extract a String value associated with the specified key on a JsonObject.
*
* @param jo The JsonObject to extract a String from
* @param key The key associated with the value to extract
* @return The value associated with {@code key}, or the empty String if {@code key} was not in {@code jo}.
*/
public static String stringFromJson(JsonObject jo, String key)
{
return jo.has(key) ? jo.get(key).getAsString() : "";
}
/**
* Convenience method, extract a double value associated with the specified key on a JsonObject.
*
* @param jo The JsonObject to extract a double from
* @param key The key associated with the value to extract
* @return The value associated with {@code key}, or 0.0 if {@code key} was not in {@code jo}.
*/
public static double doubleFromJson(JsonObject jo, String key)
{
return jo.has(key) ? jo.get(key).getAsDouble() : 0;
}
/**
* Convenience method, extract an int value associated with the specified key on a JsonObject.
*
* @param jo The JsonObject to extract an int from
* @param key The key associated with the value to extract
* @return The value associated with {@code key}, or 0 if {@code key} was not in {@code jo}.
*/
public static int intFromJson(JsonObject jo, String key)
{
return jo.has(key) ? jo.get(key).getAsInt() : 0;
}
/**
* Convenience method, extract a boolean value associated with the specified key on a JsonObject.
*
* @param jo The JsonObject to extract a boolean from
* @param key The key associated with the value to extract
* @return The value associated with {@code key}, or false if {@code key} was not in {@code jo}.
*/
public static boolean booleanFromJson(JsonObject jo, String key)
{
return jo.has(key) ? jo.get(key).getAsBoolean() : false;
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools/selenium/MatchUtils.java
|
package ai.devtools.selenium;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.openqa.selenium.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonObject;
import ai.devtools.selenium.CollectionUtils.Tuple;
/**
* Static methods for matching bounding boxes to underlying Selenium elements.
*/
class MatchUtils
{
/**
* The logger for this class
*/
private static Logger log = LoggerFactory.getLogger(MatchUtils.class);
/**
* Matches a bounding box returned by the dev-tools.ai API to a selenium WebElement on the current page.
*
* @param boundingBox The json representing the element returned by the dev-tools.ai API.
* @param driver The {@code SmartDriver} to use
* @return The best-matching, underlying {@code WebElement} which best fits the parameters specified by {@code boudingBox}
*/
public static WebElement matchBoundingBoxToSeleniumElement(JsonObject boundingBox, SmartDriver driver)
{
HashMap<String, Double> newBox = new HashMap<>();
newBox.put("x", boundingBox.get("x").getAsDouble() / driver.multiplier);
newBox.put("y", boundingBox.get("y").getAsDouble() / driver.multiplier);
newBox.put("width", boundingBox.get("width").getAsDouble() / driver.multiplier);
newBox.put("height", boundingBox.get("height").getAsDouble() / driver.multiplier);
List<WebElement> elements = driver.driver.findElements(By.xpath("//*"));
List<Double> iouScores = new ArrayList<>();
for (WebElement e : elements)
try
{
iouScores.add(iouBoxes(newBox, e.getRect()));
}
catch (StaleElementReferenceException x)
{
log.debug("Stale reference to element '{}', setting score of 0", e);
iouScores.add(0.0);
}
List<Tuple<Double, WebElement>> composite = new ArrayList<>();
for (int i = 0; i < iouScores.size(); i++)
composite.add(new Tuple<>(iouScores.get(i), elements.get(i)));
Collections.sort(composite, (o1, o2) -> o2.k.compareTo(o1.k)); // sort the composite values in reverse (descending) order
composite = composite.stream().filter(x -> x.k > 0).filter(x -> centerHit(newBox, x.v.getRect())).collect(Collectors.toList());
if (composite.size() == 0)
throw new NoSuchElementException("Could not find any web element under the center of the bounding box");
for (Tuple<Double, WebElement> t : composite)
if (t.v.getTagName().equals("input") || t.v.getTagName().equals(("button")) && t.k > composite.get(0).k * 0.9)
return t.v;
return composite.get(0).v;
}
/**
* Calculate the IOU score of two rectangles. This is derived from the overlap and areas of both rectangles.
*
* @param box1 The first box The first rectangle to check (the json returned from the dev-tools.ai API)
* @param box2 The second box The second rectangle to check (the Rectangle from the selenium WebElement)
* @return The IOU score of the two rectangles. Higher score means relative to other scores (obtained from comparisons between other pairs of rectangles) means better match.
*/
private static double iouBoxes(Map<String, Double> box1, Rectangle box2)
{
return iou(box1.get("x"), box1.get("y"), box1.get("width"), box1.get("height"), (double) box2.x, (double) box2.y, (double) box2.width, (double) box2.height);
}
/**
* Calculate the IOU score of two rectangles. This is derived from the overlap and areas of both rectangles.
*
* @param x The x coordinate of the first box (upper left corner)
* @param y The y coordinate of the first box (upper left corner)
* @param w The width of the first box
* @param h The height of the first box
* @param xx The x coordinate of the second box (upper left corner)
* @param yy The y coordinate of the second box (upper left corner)
* @param ww The width of the second box
* @param hh The height of the second box
* @return The IOU value of both boxes.
*/
private static double iou(double x, double y, double w, double h, double xx, double yy, double ww, double hh)
{
double overlap = areaOverlap(x, y, w, h, xx, yy, ww, hh);
return overlap / (area(w, h) + area(ww, hh) - overlap);
}
/**
* Determines the amount of area overlap between two rectangles
*
* @param x The x coordinate of the first box (upper left corner)
* @param y The y coordinate of the first box (upper left corner)
* @param w The width of the first box
* @param h The height of the first box
* @param xx The x coordinate of the second box (upper left corner)
* @param yy The y coordinate of the second box (upper left corner)
* @param ww The width of the second box
* @param hh The height of the second box
* @return The amount of overlap, in square pixels.
*/
private static double areaOverlap(double x, double y, double w, double h, double xx, double yy, double ww, double hh)
{
double dx = Math.min(x + w, xx + ww) - Math.max(x, xx), dy = Math.min(y + h, yy + hh) - Math.max(y, yy);
return dx >= 0 && dy >= 0 ? dx * dy : 0;
}
/**
* Convenience function, calculates the area of a rectangle
*
* @param w The width of the rectangle
* @param h The height of the rectangle
* @return The area of the rectangle
*/
private static double area(double w, double h)
{
return w * h;
}
/**
* Determines if center point of {@code box1} falls within the area of {@code box2}
*
* @param box1 The first rectangle to check (the json returned from the dev-tools.ai API)
* @param box2 The second rectangle to check (the Rectangle from the selenium WebElement)
* @return {@code true} if the center point of {@code box1} falls within the area of {@code box2}
*/
private static boolean centerHit(Map<String, Double> box1, Rectangle box2)
{
double centerX = box1.get("x") + box1.get("width") / 2, centerY = box1.get("y") + box1.get("height") / 2;
return centerX > box2.x && centerX < box2.x + box2.width && centerY > box2.y && centerY < box2.y + box2.height;
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools/selenium/NetUtils.java
|
package ai.devtools.selenium;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.HashMap;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import okhttp3.*;
/**
* Shared network/http-related utilities and functionality
*/
final class NetUtils
{
/**
* The {@code MediaType} representing the json MIME type.
*/
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
/**
* Performs a simple POST to the specified url with the provided client and {@code RequestBody}.
*
* @param client The OkHttp client to use
* @param baseURL The base URL to target
* @param endpoint The endpoint on the baseURL to target.
* @param b The request body to POST.
* @return The response from the server, in the form of a {@code Response} object
* @throws IOException Network error
*/
private static Response basicPOST(OkHttpClient client, HttpUrl baseURL, String endpoint, RequestBody b) throws IOException
{
return client.newCall(new Request.Builder().url(baseURL.newBuilder().addPathSegment(endpoint).build()).post(b).build()).execute();
}
public static JsonObject post(String url, JsonObject json) throws IOException
{
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(Duration.ofSeconds(30)).readTimeout(Duration.ofSeconds(30)).build();
RequestBody payload = new FormBody.Builder().add("json", json.toString()).build();
Request request = new Request.Builder()
.url(url)
.post(payload)
.build();
Call call = client.newCall(request);
try (Response response = client.newCall(request).execute()) {
return new Gson().fromJson(response.body().string(), JsonObject.class);
} catch (IOException e) {
throw e;
}
}
/**
* Performs a simple POST to the specified url with the provided client and json data.
*
* @param client The OkHttp client to use
* @param baseURL The base URL to target
* @param endpoint The endpoint on the baseURL to target.
* @param jo The JsonObject to put in the request body
* @return The response from the server, in the form of a {@code Response} object
* @throws IOException Network error
*/
public static Response basicPOST(OkHttpClient client, HttpUrl baseURL, String endpoint, JsonObject jo) throws IOException
{
return basicPOST(client, baseURL, endpoint, RequestBody.create(jo.toString(), JSON));
}
/**
* Performs a simple form POST to the specified url with the provided client and form data.
*
* @param client The OkHttp client to use
* @param baseURL The base URL to target
* @param endpoint The endpoint on the baseURL to target.
* @param form The form data to POST
* @return The response from the server, in the form of a {@code Response} object
* @throws IOException Network error
*/
public static Response basicPOST(OkHttpClient client, HttpUrl baseURL, String endpoint, HashMap<String, String> form) throws IOException
{
FormBody.Builder fb = new FormBody.Builder();
form.forEach(fb::add);
return basicPOST(client, baseURL, endpoint, fb.build());
}
/**
* Convenience method, creates a new OkHttpBuilder with timeouts configured.
*
* @return A OkHttpClient builder with reasonable timeouts configured.
*/
static OkHttpClient.Builder basicClient()
{
Duration d = Duration.ofSeconds(60);
return new OkHttpClient.Builder().connectTimeout(d).writeTimeout(d).readTimeout(d).callTimeout(d);
}
/**
* Creates a new {@code OkHttpClient} which ignores expired/invalid ssl certificates. Normally, OkHttp will raise an exception if it encounters bad certificates.
*
* @return A new {@code OkHttpClient} which ignores expired/invalid ssl certificates.
*/
public static OkHttpClient unsafeClient()
{
try
{
TrustManager tl[] = { new TrustAllX509Manager() };
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, tl, new SecureRandom());
return basicClient().sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) tl[0]).hostnameVerifier(new TrustAllHostnameVerifier()).build();
}
catch (Throwable e) // highly unlikely, shut up compiler
{
return null;
}
}
/**
* A dummy {@code HostnameVerifier} which doesn't actually do any hostname checking.
*
* @author Alexander Wu (alec@dev-tools.ai)
*
*/
private static class TrustAllHostnameVerifier implements HostnameVerifier
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
}
/**
* A dummy {@code X509TrustManager} which doesn't actually do any certificate verification.
*
* @author Alexander Wu (alec@dev-tools.ai)
*
*/
private static class TrustAllX509Manager implements 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 new X509Certificate[0];
}
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools/selenium/SmartDriver.java
|
package ai.devtools.selenium;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.logging.Level;
import java.awt.Desktop;
import java.net.URI;
import javax.imageio.ImageIO;
import com.google.gson.JsonNull;
import org.openqa.selenium.*;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.interactions.Sequence;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.ErrorHandler;
import org.openqa.selenium.remote.FileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.SessionId;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.slf4j.helpers.MessageFormatter;
import com.google.gson.JsonObject;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
/**
* The {@code SmartDriver} class is a wrapper around a {@code RemoteWebDriver} that uses the results of the dev-tools.ai classifier for improved robustness, finding elements visually and avoiding broken selectors.
*/
@SuppressWarnings("deprecation")
public class SmartDriver extends RemoteWebDriver {
/**
* The current version of the SDK
*/
private static String SDK_VERSION = "0.1.11";
/**
* The logger for this class
*/
private Logger log = Logger.getLogger(SmartDriver.class);
/**
* The client to use for making http requests
*/
private OkHttpClient client;
/**
* The driver used by the user that we're wrapping.
*/
RemoteWebDriver driver;
/**
* The user's Smartdriver API key
*/
private String apiKey;
/**
* The base URL of the target server (e.g. {@code https://smartdriver.dev-tools.ai})
*/
private HttpUrl serverURL;
private String prodUrl = "https://smartdriver.dev-tools.ai";
/**
* The test case name. Used in live/interactive mode.
*/
private String testCaseName;
/**
* The UUID of the last screenshot in live/interactive mode.
*/
private String lastTestCaseScreenshotUUID;
/**
* The screen density multiplier
*/
double multiplier;
private Dimension windowSize;
private Dimension imSize;
private Boolean useClassifierDuringCreation;
private Boolean testCaseCreationMode;
private String refScreenshotUUID;
private float pageOffset;
private float previousPageOffset;
/**
* Constructor, creates a new SmartDriver.
*
* @param driver The {@code RemoteWebDriver} to wrap
* @param apiKey Your API key, acquired from <a href="https://smartdriver.dev-tools.ai">smartdriver.dev-tools.ai</a>.
* @param initializationDict The configuration options for the driver.
* @throws IOException If there was an initialization error.
*/
public SmartDriver(RemoteWebDriver driver, String apiKey, Map<String, Object> initializationDict) throws IOException
{
this.driver = driver;
this.apiKey = apiKey;
log.setLevel(org.apache.log4j.Level.INFO);
BasicConfigurator.configure();
this.testCaseName = (String) initializationDict.get("testCaseName");
this.useClassifierDuringCreation = (Boolean) initializationDict.get("useClassifierDuringCreation");
this.testCaseCreationMode = Utils.StrToBool(System.getenv("DEVTOOLSAI_INTERACTIVE"));
if (testCaseName == null)
{
StackTraceElement[] sl = Thread.currentThread().getStackTrace();
if (sl.length > 0)
{
StackTraceElement bottom = sl[sl.length - 1];
this.testCaseName = String.format("%s.%s", bottom.getClassName(), bottom.getMethodName());
log.info("No test case name was specified, defaulting to " + this.testCaseName);
}
else
this.testCaseName = "My first test case";
}
String baseUrl = (String) initializationDict.get("serverURL");
this.serverURL = HttpUrl.parse(baseUrl != null ? baseUrl : Objects.requireNonNullElse(System.getenv("DEVTOOLSAI_URL"), prodUrl));
client = this.serverURL.equals(HttpUrl.parse("https://smartdriver.dev-tools.ai")) ? NetUtils.unsafeClient() : NetUtils.basicClient().build();
windowSize = driver.manage().window().getSize();
BufferedImage im = ImageIO.read(driver.getScreenshotAs(OutputType.FILE));
imSize = new Dimension(im.getWidth(), im.getHeight());
multiplier = 1.0 * imSize.width / windowSize.width;
log.debug("The screen multiplier is " + multiplier);
try
{
JsonObject payload = CollectionUtils.keyValuesToJO("api_key", apiKey, "os",
String.format("%s-%s-%s", System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")), "sdk_version", SDK_VERSION, "language",
String.format("java-%s", System.getProperty("java.version")), "test_case_name", this.testCaseName);
log.debug(MessageFormatter.format("Checking in with: {}", payload.toString()).toString());
JsonObject r = JsonUtils.responseAsJson(NetUtils.basicPOST(client, this.serverURL, "ping", payload));
if (!JsonUtils.booleanFromJson(r, "success"))
log.debug(MessageFormatter.format("Error during checkin, server said: {}", r.toString()).getMessage());
}
catch (Throwable e)
{
log.debug(MessageFormatter.format("Checkin failed catastrophically: {}", e.getMessage()).getMessage());
}
}
/**
* Constructor, creates a new SmartDriver with the default server url (<a href="https://smartdriver.dev-tools.ai">smartdriver.dev-tools.ai</a>), non-interactive mode, and with training enabled.
*
* @param driver The {@code RemoteWebDriver} to wrap
* @param apiKey Your API key, acquired from <a href="https://smartdriver.dev-tools.ai">smartdriver.dev-tools.ai</a>.
* @throws IOException If there was an initialization error.
*/
public SmartDriver(RemoteWebDriver driver, String apiKey) throws IOException
{
this(driver, apiKey, new HashMap<String, Object>());
}
/**
* Convenience method, implicitly wait for the specified amount of time.
*
* @param waitTime The number of seconds to implicitly wait.
* @return This {@code SmartDriver}, for chaining convenience.
*/
public SmartDriver implicitlyWait(long waitTime)
{
driver.manage().timeouts().implicitlyWait(waitTime, TimeUnit.SECONDS);
return this;
}
@Override
public Object executeAsyncScript(String script, Object... args)
{
return driver.executeAsyncScript(script, args);
}
@Override
public Object executeScript(String script, Object... args)
{
return driver.executeScript(script, args);
}
/**
* Opens a web browser and directs it to {@code url}.
*
* @param url The URL to launch the browser to.
*/
@Override
public void get(String url)
{
driver.get(url);
}
public WebElement findElement(By locator, String elementName)
{
if (elementName == null) {
elementName = String.format("element_name_by_locator_%s", locator.toString().replace('.', '_').replace(' ', '_'));
}
try
{
WebElement driverElement = driver.findElement(locator);
if (driverElement != null)
{
String key = uploadScreenshotIfNecessary(elementName, driverElement);
if (key != null) {
updateElement(driverElement, key, elementName, true);
}
}
return driverElement;
}
catch (Throwable x)
{
log.info(MessageFormatter.format("Element '{}' was not found by Selenium, trying with Smartdriver...", elementName).getMessage());
ClassifyResult result = classify(elementName);
if (result.e != null) {
return result.e;
} else {
log.error(result.msg);
}
log.error(MessageFormatter.format("Smartdriver was also unable to find the element with name '{}'", elementName).getMessage());
throw x;
}
}
@Override
public WebElement findElement(By locator)
{
return findElement(locator, null);
}
@Override
public List<WebElement> findElements(By locator)
{
return driver.findElements(locator);
}
@Override
public Capabilities getCapabilities()
{
return driver.getCapabilities();
}
@Override
public CommandExecutor getCommandExecutor()
{
return driver.getCommandExecutor();
}
@Override
public String getCurrentUrl()
{
return driver.getCurrentUrl();
}
@Override
public ErrorHandler getErrorHandler()
{
return driver.getErrorHandler();
}
@Override
public FileDetector getFileDetector()
{
return driver.getFileDetector();
}
@Override
public String getPageSource()
{
return driver.getPageSource();
}
@Override
public <X> X getScreenshotAs(OutputType<X> outputType)
{
return driver.getScreenshotAs(outputType);
}
@Override
public SessionId getSessionId()
{
return driver.getSessionId();
}
@Override
public String getTitle()
{
return driver.getTitle();
}
@Override
public String getWindowHandle()
{
return driver.getWindowHandle();
}
@Override
public Set<String> getWindowHandles()
{
return driver.getWindowHandles();
}
@Override
public Options manage()
{
return driver.manage();
}
@Override
public Navigation navigate()
{
return driver.navigate();
}
@Override
public void perform(Collection<Sequence> actions)
{
driver.perform(actions);
}
@Override
public void quit()
{
driver.quit();
}
@Override
public void resetInputState()
{
driver.resetInputState();
}
@Override
public void setErrorHandler(ErrorHandler handler)
{
driver.setErrorHandler(handler);
}
@Override
public void setFileDetector(FileDetector detector)
{
driver.setFileDetector(detector);
}
@Override
public void setLogLevel(Level level)
{
driver.setLogLevel(level);
}
@Override
public TargetLocator switchTo()
{
return driver.switchTo();
}
@Override
public String toString()
{
return driver.toString();
}
/**
* Attempts to find an element by class name.
*
* @param using The class name of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByClassName(String using, String elementName)
{
return this.findElement(By.className(using), elementName);
}
/**
* Attempts to find an element by class name.
*
* @param using The class name of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByClassName(String using)
{
return findElementByClassName(using, null);
}
/**
* Attempts to find all elements with the matching class name.
*
* @param using The class name of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByClassName(String using)
{
return driver.findElements(By.className(using));
}
/**
* Attempts to find an element by css selector.
*
* @param using The css selector of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByCssSelector(String using, String elementName)
{
return this.findElement(By.cssSelector(using), elementName);
}
/**
* Attempts to find an element by css selector.
*
* @param using The css selector of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByCssSelector(String using)
{
return findElementByCssSelector(using, null);
}
/**
* Attempts to find all elements with the matching css selector.
*
* @param using The css selector of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByCssSelector(String using)
{
return driver.findElements(By.cssSelector(using));
}
/**
* Attempts to find an element by id.
*
* @param using The id of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementById(String using, String elementName)
{
return findElement(By.id(using), elementName);
}
/**
* Attempts to find an element by id.
*
* @param using The id of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementById(String using)
{
return findElementById(using, null);
}
/**
* Attempts to find all elements with the matching id.
*
* @param using The id of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsById(String using)
{
return driver.findElements(By.id(using));
}
/**
* Attempts to find an element by link text.
*
* @param using The link text of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByLinkText(String using, String elementName)
{
return findElement(By.linkText(using), elementName);
}
/**
* Attempts to find an element by link text.
*
* @param using The link text of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByLinkText(String using)
{
return findElementByLinkText(using, null);
}
/**
* Attempts to find all elements with the matching link text.
*
* @param using The link text of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByLinkText(String using)
{
return driver.findElements(By.linkText(using));
}
/**
* Attempts to find an element by name.
*
* @param using The name of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByName(String using, String elementName)
{
return findElement(By.name(using), elementName);
}
/**
* Attempts to find an element by name.
*
* @param using The name of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByName(String using)
{
return findElementByName(using, null);
}
/**
* Attempts to find all elements with the matching name.
*
* @param using The name of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByName(String using)
{
return driver.findElements(By.name(using));
}
/**
* Attempts to find an element by partial link text.
*
* @param using The partial link text of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByPartialLinkText(String using, String elementName)
{
return findElement(By.partialLinkText(using), elementName);
}
/**
* Attempts to find an element by partial link text.
*
* @param using The partial link text of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByPartialLinkText(String using)
{
return findElementByPartialLinkText(using, null);
}
/**
* Attempts to find all elements with the matching partial link text.
*
* @param using The partial link text of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByPartialLinkText(String using)
{
return driver.findElements(By.partialLinkText(using));
}
/**
* Attempts to find an element by tag name.
*
* @param using The tag name of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByTagName(String using, String elementName)
{
return findElement(By.tagName(using), elementName);
}
/**
* Attempts to find an element by tag name.
*
* @param using The tag name of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByTagName(String using)
{
return findElementByTagName(using, null);
}
/**
* Attempts to find all elements with the matching tag name.
*
* @param using The tag name of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByTagName(String using)
{
return driver.findElements(By.tagName(using));
}
/**
* Attempts to find an element by xpath.
*
* @param using The xpath of the element to find
* @param elementName The label name of the element to be classified. Optional, set {@code null} to auto generate an element name.
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByXPath(String using, String elementName)
{
return findElement(By.xpath(using), elementName);
}
/**
* Attempts to find an element by xpath.
*
* @param using The xpath of the element to find
* @return The element that was found. Raises an exception otherwise.
*/
public WebElement findElementByXPath(String using)
{
return findElementByXPath(using, null);
}
/**
* Attempts to find all elements with the matching xpath.
*
* @param using The xpath of the elements to find.
* @return A {@code List} with any elements that were found, or an empty {@code List} if no matches were found.
*/
public List<WebElement> findElementsByXPath(String using)
{
return driver.findElements(By.xpath(using));
}
/**
* Finds an element by {@code elementName}. Please use {@link #findElementByElementName(String)} instead.
*
* @param elementName The label name of the element to be classified.
* @return An element associated with {@code elementName}. Throws NoSuchElementException otherwise.
*/
public WebElement findByElementName(String elementName)
{
return findElementByElementName(elementName);
}
/**
* Finds an element by {@code elementName}.
*
* @param elementName The label name of the element to be classified.
* @return An element associated with {@code elementName}. Throws NoSuchElementException otherwise.
*/
public WebElement findElementByElementName(String elementName)
{
ClassifyResult r = classify(elementName);
if (r.e == null)
throw new NoSuchElementException(r.msg);
return r.e;
}
/**
* Finds an elements by {@code elementName}. Uses visual AI to find the element.
*
* @param elementName The label name of the element to be classified.
* @return An element associated with {@code elementName}. Throws NoSuchElementException otherwise.
*/
public WebElement findByAI(String elementName)
{
return findElementByElementName(elementName);
}
private String getScreenshotHash(String screenshotBase64) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5sum = md.digest(screenshotBase64.getBytes());
String output = String.format("%032X", new BigInteger(1, md5sum));
return output.toLowerCase();
} catch (Throwable e) {
return "";
}
}
private JsonObject checkScreenshotExists(String screenshotUUID, String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot_uuid", screenshotUUID);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "exists_screenshot", payload));
return res;
} catch (Throwable e) {
log.debug("Error checking if screenshot exists");
e.printStackTrace();
return null;
}
}
private JsonObject uploadScreenshot(String screenshotBase64,String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "upload_screenshot", payload));
return res;
} catch (Throwable e) {
log.debug("Error uploading screenshot");
e.printStackTrace();
return null;
}
}
private JsonObject uploadTCScreenshot(String screenshotBase64, String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
payload.addProperty("is_interactive", true);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "upload_screenshot", payload));
return res;
} catch (Throwable e) {
log.debug("Error uploading test case screenshot");
e.printStackTrace();
return null;
}
}
public void scrollToElement(WebElement element, Boolean scrollUp) {
if(scrollUp) {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(false);", element);
} else {
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
}
}
public void scrollPage(int amount) {
((JavascriptExecutor) driver).executeScript("window.scrollBy(0, " + amount + ")");
}
private String uploadScreenshotIfNecessary(String elementName, WebElement element) {
Boolean isElementFrozen = checkIfFrozen(elementName);
if (isElementFrozen) {
return null;
} else {
String screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
String screenshotUUID = getScreenshotHash(screenshotBase64);
refScreenshotUUID = null;
pageOffset = 0f;
if (element != null) {
pageOffset = getPageOffset();
Boolean needsToScroll = (element.getRect().getY() > (windowSize.getHeight() + pageOffset)) || (element.getRect().getY() < pageOffset);
if(needsToScroll) {
previousPageOffset = pageOffset;
refScreenshotUUID = screenshotUUID;
scrollToElement(element, element.getRect().getY() < pageOffset);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
screenshotUUID = getScreenshotHash(screenshotBase64);
pageOffset = getPageOffset();
scrollPage((int) (previousPageOffset - pageOffset));
}
}
JsonObject screenshotExistsResponse = checkScreenshotExists(screenshotUUID, elementName);
if (screenshotExistsResponse != null && screenshotExistsResponse.get("exists_screenshot").getAsBoolean()) {
return screenshotUUID;
} else {
JsonObject uploadScreenshotResponse = uploadScreenshot(screenshotBase64, elementName);
if (uploadScreenshotResponse != null) {
if (uploadScreenshotResponse.get("success").getAsBoolean()) {
return uploadScreenshotResponse.get("screenshot_uuid").getAsString();
} else {
log.info("Error uploading screenshot");
return screenshotUUID;
}
} else {
log.info("Error uploading screenshot");
return screenshotUUID;
}
}
}
}
private Boolean checkIfFrozen(String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "check_frozen", payload));
return res.get("is_frozen").getAsBoolean();
} catch (Throwable e) {
log.debug("Error checking if element is frozen");
e.printStackTrace();
return true;
}
}
/**
* Shared {@code findElementBy} functionality. This serves as the base logic for most find by methods exposed to the end user.
*
* @param using The search term to use when looking for an element.
* @param elementName The label name of the element to be classified. This is what the element will be stored under in the dev-tools.ai db.
* @param shortcode The short identifier for the type of lookup being performed. This will be used to aut-generate an {@code elementName} if the user did not specify one.
* @param fn The selenium function to call with {@code using}, which will be used to fetch what selenium thinks is the target element.
* @return The SmartDriverElement
*/
private WebElement findElementByGeneric(String using, String elementName, String shortcode, Function<String, WebElement> fn)
{
if (elementName == null) {
elementName = String.format("element_name_by_%s_%s", shortcode, using.replace('.', '_'));
}
try
{
WebElement driverElement = fn.apply(using);
if (driverElement != null)
{
String key = uploadScreenshotIfNecessary(elementName, driverElement);
if (key != null) {
updateElement(driverElement, key, elementName, true);
}
}
return driverElement;
}
catch (Throwable x)
{
log.info(MessageFormatter.format("Element '{}' was not found by Selenium, trying with Smartdriver...", elementName).getMessage());
ClassifyResult result = classify(elementName);
if (result.e != null) {
return result.e;
} else {
log.error(result.msg);
}
log.error(MessageFormatter.format("Smartdriver was also unable to find the element with name '{}'", elementName).getMessage());
throw x;
}
}
/**
* Updates the entry for an element as it is known to the dev-tools.ai servers.
*
* @param elem The element to update
* @param screenshotUUID The key associated with this element
* @param elementName The name associated with this element
* @param trainIfNecessary Set {@code true} if the model on the server should also be trained with this element.
*/
protected void updateElement(WebElement elem, String screenshotUUID, String elementName, boolean trainIfNecessary)
{
Rectangle rect = elem.getRect();
JsonObject payload = new JsonObject();
payload.addProperty("screenshot_uuid", screenshotUUID);
payload.addProperty("retrain", trainIfNecessary);
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("x", rect.x * multiplier);
payload.addProperty("y", rect.y * multiplier);
payload.addProperty("width", rect.width * multiplier);
payload.addProperty("height", rect.height * multiplier);
payload.addProperty("multiplier", multiplier);
payload.addProperty("test_case_name", testCaseName);
payload.addProperty("page_offset", this.pageOffset * this.multiplier);
payload.addProperty("ref_screenshot_uuid", this.refScreenshotUUID);
try {
JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "add_action_info", payload));
} catch (Throwable e) {
log.debug("Error updating element");
e.printStackTrace();
}
}
private JsonObject getTCBox(String elementName) {
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot_uuid", lastTestCaseScreenshotUUID);
payload.addProperty("run_classifier", useClassifierDuringCreation);
try {
JsonObject res = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "testcase/get_action_info", payload));
return res;
} catch (Throwable e) {
log.debug("Error getting TC box");
e.printStackTrace();
return null;
}
}
private void openBrowser(String url) {
try {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("mac")) {
Runtime.getRuntime().exec("open " + url);
} else if (os.contains("windows")) {
Desktop.getDesktop().browse(new URI(url));
} else {
log.info(MessageFormatter.format("Please open the following URL in your browser: {}", url).getMessage());
}
} catch (Throwable e) {
log.info(MessageFormatter.format("Please open the following URL in your browser: {}", url).getMessage());
}
}
/**
* Perform additional classification on an element by querying the dev-tools.ai server.
*
* @param elementName The name of the element to run classification on.
* @return The result of the classification.
*/
protected ClassifyResult classify(String elementName)
{
if(testCaseCreationMode) {
String screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
JsonObject res = uploadTCScreenshot(screenshotBase64, elementName);
if (res.get("success").getAsBoolean()) {
lastTestCaseScreenshotUUID = res.get("screenshot_uuid").getAsString();
JsonObject boxResponse = getTCBox(elementName);
if (boxResponse != null && boxResponse.get("success").getAsBoolean() && boxResponse.get("predicted_element") != JsonNull.INSTANCE) {
return new ClassifyResult(new SmartDriverElement(boxResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()), lastTestCaseScreenshotUUID);
} else {
// label_url = self.url + '/testcase/label?test_case_name=' + urllib.parse.quote(self.test_case_uuid)
String labelUrl = serverURL + "/testcase/label?test_case_name=" + URLEncoder.encode(testCaseName);
openBrowser(labelUrl);
while (true) {
boxResponse = getTCBox(elementName);
if (boxResponse != null && boxResponse.get("success").getAsBoolean() && boxResponse.get("predicted_element") != JsonNull.INSTANCE) {
return new ClassifyResult(new SmartDriverElement(boxResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()), lastTestCaseScreenshotUUID);
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} else {
log.info("Failed to upload test case screenshot");
log.info(res.get("message").getAsString());
return new ClassifyResult(null, lastTestCaseScreenshotUUID, res.get("message").getAsString());
}
} else {
String pageSource = "", msg = "Smartdriver driver exception", key = null;
try {
String screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
String screenshotUUID = getScreenshotHash(screenshotBase64);
JsonObject screenshotExistsResponse = checkScreenshotExists(screenshotUUID, elementName);
if (screenshotExistsResponse != null && screenshotExistsResponse.get("success").getAsBoolean() && screenshotExistsResponse.get("predicted_element") != JsonNull.INSTANCE) {
msg = screenshotExistsResponse.get("message").getAsString();
log.info(msg);
float currentOffset = getPageOffset();
float bottomOffset = currentOffset + windowSize.height;
float realOffset = (float) (screenshotExistsResponse.get("page_offset").getAsFloat() / multiplier);
if (realOffset > bottomOffset || realOffset < currentOffset) {
int scrollOffset = (int) (realOffset - currentOffset);
// Scroll
scrollPage((int) scrollOffset);
Thread.sleep(1000);
screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
screenshotUUID = getScreenshotHash(screenshotBase64);
screenshotExistsResponse = checkScreenshotExists(screenshotUUID, elementName);
}
if (screenshotExistsResponse != null && screenshotExistsResponse.get("success").getAsBoolean() && screenshotExistsResponse.get("predicted_element") != JsonNull.INSTANCE) {
return new ClassifyResult(new SmartDriverElement(screenshotExistsResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()), null);
}
}
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
JsonObject classifyResponse = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "detect", payload));
if (!classifyResponse.get("success").getAsBoolean()) {
classifyResponse = classifyFullScreen(elementName, screenshotBase64);
if (!classifyResponse.get("success").getAsBoolean()) {
log.info(classifyResponse.get("message").getAsString());
return new ClassifyResult(null, null, classifyResponse.get("message").getAsString());
}
}
msg = classifyResponse.get("message").getAsString().replace(prodUrl, serverURL.toString());
log.info(msg);
try {
return new ClassifyResult(new SmartDriverElement(classifyResponse.get("predicted_element").getAsJsonObject(), this, getPageOffset()),
classifyResponse.get("screenshot_uuid").getAsString());
} catch (Throwable e) {
log.error("Error creating SmartDriverElement from response");
e.printStackTrace();
return new ClassifyResult(null, key, msg);
}
} catch (Throwable e) {
e.printStackTrace();
}
log.warn(msg);
return new ClassifyResult(null, key, msg);
}
}
private float getPageOffset(){
Object res = driver.executeScript("return window.pageYOffset;");
if (res instanceof Number) {
return ((Number) res).floatValue();
} else {
return 0;
}
}
JsonObject classifyFullScreen(String elementName, String screenshotBase64) {
int lastOffset = -1;
int offset = 1;
int windowHeight = windowSize.height;
scrollPage(-100000);
JsonObject r = new JsonObject();
r.addProperty("success", false);
while(offset > lastOffset) {
lastOffset = offset;
screenshotBase64 = driver.getScreenshotAs(OutputType.BASE64);
JsonObject payload = new JsonObject();
payload.addProperty("api_key", apiKey);
payload.addProperty("label", elementName);
payload.addProperty("screenshot", screenshotBase64);
payload.addProperty("test_case_name", testCaseName);
try {
r = JsonUtils.responseAsJson(NetUtils.basicPOST(client, serverURL, "detect", payload));
if (r.get("success").getAsBoolean()) {
return r;
}
} catch (Throwable e) {
log.error("Error creating SmartDriverElement from response");
e.printStackTrace();
return r;
}
scrollPage((int) windowHeight);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
offset = (int) getPageOffset();
}
return r;
}
/**
* Simple container for encapsulating results of calls to {@code classify()}.
*
*/
private static class ClassifyResult
{
/**
* The SmartDriverElement created by the call to classify
*/
public SmartDriverElement e;
/**
* The key returned by the call to classify
*/
public String key;
/**
* The message associated with this result
*/
public String msg;
/**
* Constructor, creates a new ClassifyResult.
*
* @param e The SmartDriverElement to to use
* @param key The key to use
* @param msg The message to associate with this result
*/
ClassifyResult(SmartDriverElement e, String key, String msg)
{
this.e = e;
this.key = key;
this.msg = msg;
}
/**
* Constructor, creates a new ClassifyResult, where the {@code msg} is set to the empty String by default.
*
* @param e
* @param key
*/
ClassifyResult(SmartDriverElement e, String key)
{
this(e, key, "");
}
}
@Override
public void close() {
driver.close();
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools/selenium/SmartDriverElement.java
|
package ai.devtools.selenium;
import com.google.gson.JsonObject;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.RemoteWebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An enhanced RemoteWebElement which uses the results of the dev-tools.ai classifier for improved accuracy.
*
*/
public class SmartDriverElement extends RemoteWebElement
{
/**
* The logger for this class
*/
private static Logger log = LoggerFactory.getLogger(SmartDriverElement.class);
/**
* The webdriver the user is using. We wrap this for when the user calls methods that interact with selenium.
*/
private RemoteWebDriver driver;
/**
* The underlying {@code WebElement} used for performing actions in the browser.
*/
private WebElement realElement;
/**
* The text in this element, as determined by dev-tools.ai's classifier
*/
private String text;
/**
* The size of this element, in pixels
*/
private Dimension size;
/**
* The location of this element, in pixels (offset from the upper left corner of the screen)
*/
private Point location;
/**
* The rectangle that can be drawn around this element. Basically combines size and location.
*/
private Rectangle rectangle;
/**
* The tag name of this element, as determined by dev-tools.ai's classifier
*/
private String tagName;
SmartDriverElement(JsonObject elem, SmartDriver driver) {
this(elem, driver, 0);
}
/**
* Constructor, creates a new SmartDriverElement
*
* @param elem The element data returned by the FD API, as JSON
* @param driver The {@code SmartDriver} to associate with this {@code SmartDriverElement}.
*/
SmartDriverElement(JsonObject elem, SmartDriver driver, float page_offset)
{
log.debug("Creating new SmartDriverElement w/ {}", elem);
this.driver = driver.driver;
int pageY = elem.get("y").getAsInt();
elem.remove("y");
elem.addProperty("y", pageY + page_offset * driver.multiplier);
this.realElement = MatchUtils.matchBoundingBoxToSeleniumElement(elem, driver);
text = JsonUtils.stringFromJson(elem, "text");
size = new Dimension(JsonUtils.intFromJson(elem, "width") / Math.max((int) driver.multiplier, 1), JsonUtils.intFromJson(elem, "height") / Math.max((int) driver.multiplier, 1));
location = new Point(JsonUtils.intFromJson(elem, "x") / Math.max((int) driver.multiplier, 1), JsonUtils.intFromJson(elem, "y") / Math.max((int) driver.multiplier, 1));
// this.property = property //TODO: not referenced/implemented on python side??
rectangle = new Rectangle(location, size);
tagName = JsonUtils.stringFromJson(elem, "class");
}
public String toString()
{
return "SmartDriverElement: " + text;
}
@Override
public String getText()
{
return text;
}
@Override
public Dimension getSize()
{
return size;
}
@Override
public Point getLocation()
{
return location;
}
@Override
public Rectangle getRect()
{
return rectangle;
}
@Override
public String getTagName()
{
return tagName;
}
@Override
public void clear()
{
realElement.clear();
}
@Override
public WebElement findElement(By by)
{
return driver.findElement(by);
}
@Override
public List<WebElement> findElements(By by)
{
return driver.findElements(by);
}
@Override
public String getAttribute(String name)
{
return realElement.getAttribute(name);
}
@Override
public String getCssValue(String propertyName)
{
return realElement.getCssValue(propertyName);
}
@Override
public boolean isDisplayed()
{
return realElement.isDisplayed();
}
@Override
public boolean isEnabled()
{
return realElement.isEnabled();
}
@Override
public boolean isSelected()
{
return realElement.isSelected();
}
@Override
public void click()
{
realElement.click();
}
@Override
public void sendKeys(CharSequence... keysToSend)
{
realElement.sendKeys(keysToSend);
}
@Override
public void submit()
{
realElement.submit();
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools/selenium/Utils.java
|
package ai.devtools.selenium;
import java.util.ArrayList;
import java.util.Arrays;
/**
* The {@code Utils} class provide a function for turning strings into Booleans.
*/
class Utils {
static Boolean StrToBool(String value) {
ArrayList<String> truthValues = new ArrayList<String>(Arrays.asList("1", "true", "yes"));
if (truthValues.contains(value != null ? value.toLowerCase() : "false")) {
return true;
} else {
return false;
}
}
}
|
0
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools
|
java-sources/ai/dev-tools/ai-devtools-selenium/0.1.11/ai/devtools/selenium/package-info.java
|
/**
* Contains the main classes for the dev-tools.ai Smartdriver SDK. These classes provide simple wrappers around existing selenium functionality to seamlessly incorporate dev-tools.ai's powerful element
* classification technology.
*/
package ai.devtools.selenium;
|
0
|
java-sources/ai/djl/android/core/0.33.0/ai/djl/android
|
java-sources/ai/djl/android/core/0.33.0/ai/djl/android/core/BitmapImageFactory.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl.android.core;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import ai.djl.modality.cv.output.BoundingBox;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.output.Joints;
import ai.djl.modality.cv.output.Mask;
import ai.djl.modality.cv.output.Point;
import ai.djl.modality.cv.output.Rectangle;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDManager;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
import ai.djl.util.RandomUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.List;
/** {@code BitmapImageFactory} is the Android implementation of {@link ImageFactory}. */
public class BitmapImageFactory extends ImageFactory {
/** {@inheritDoc} */
@Override
public Image fromFile(Path path) throws IOException {
Bitmap bitmap = BitmapFactory.decodeFile(path.toString());
if (bitmap == null) {
throw new IOException("Failed to read image from: " + path);
}
return new BitMapWrapper(bitmap);
}
/** {@inheritDoc} */
@Override
public Image fromUrl(URL url) throws IOException {
return fromInputStream(url.openStream());
}
/** {@inheritDoc} */
@Override
public Image fromInputStream(InputStream is) throws IOException {
Bitmap bitmap = BitmapFactory.decodeStream(is);
if (bitmap == null) {
throw new IOException("Failed to read image from input stream");
}
return new BitMapWrapper(bitmap);
}
/** {@inheritDoc} */
@Override
public Image fromImage(Object image) {
if (!(image instanceof Bitmap)) {
throw new IllegalArgumentException("only Bitmap allowed");
}
return new BitMapWrapper((Bitmap) image);
}
/** {@inheritDoc} */
@Override
public Image fromNDArray(NDArray array) {
Shape shape = array.getShape();
if (shape.dimension() != 3) {
throw new IllegalArgumentException("Shape should only have three dimension follow CHW");
} else if (shape.get(0) == 1 || shape.get(2) == 1) {
throw new UnsupportedOperationException("Grayscale image is not supported");
}
int[] raw = array.toType(DataType.UINT8, false).toUint8Array();
if (NDImageUtils.isCHW(shape)) {
int height = (int) shape.get(1);
int width = (int) shape.get(2);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int imageArea = width * height;
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
int index = h * width + w;
int red = raw[index] & 0xFF;
int green = raw[imageArea + index] & 0xFF;
int blue = raw[imageArea * 2 + index] & 0xFF;
bitmap.setPixel(w, h, Color.argb(255, red, green, blue));
}
}
return new BitMapWrapper(bitmap);
}
int height = (int) shape.get(0);
int width = (int) shape.get(1);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
int pos = (h * width + w) * 3;
int red = raw[pos];
int green = raw[pos + 1];
int blue = raw[pos + 2];
bitmap.setPixel(w, h, Color.argb(255, red, green, blue));
}
}
return new BitMapWrapper(bitmap);
}
/** {@inheritDoc} */
@Override
public Image fromPixels(int[] pixels, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
return new BitMapWrapper(bitmap);
}
static class BitMapWrapper implements Image {
private Bitmap bitmap;
BitMapWrapper(Bitmap bitmap) {
this.bitmap = bitmap;
}
/** {@inheritDoc} */
@Override
public int getWidth() {
return bitmap.getWidth();
}
/** {@inheritDoc} */
@Override
public int getHeight() {
return bitmap.getHeight();
}
/** {@inheritDoc} */
@Override
public Bitmap getWrappedImage() {
return bitmap;
}
/** {@inheritDoc} */
@Override
public BitMapWrapper resize(int width, int height, boolean copy) {
if (!copy && bitmap.getWidth() == width && bitmap.getHeight() == height) {
return this;
}
return new BitMapWrapper(Bitmap.createScaledBitmap(bitmap, width, height, true));
}
/** {@inheritDoc} */
@Override
public Image getMask(int[][] mask) {
int w = mask[0].length;
int h = mask.length;
BitMapWrapper resized = resize(w, h, true);
Bitmap img = resized.getWrappedImage();
int[] pixels = new int[w * h];
int index = 0;
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
if (mask[y][x] != 0) {
pixels[index] = img.getPixel(x, y);
}
index++;
}
}
return new BitMapWrapper(Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888));
}
/** {@inheritDoc} */
@Override
public Image getSubImage(int x, int y, int w, int h) {
return new BitMapWrapper(Bitmap.createBitmap(bitmap, x, y, w, h));
}
/** {@inheritDoc} */
@Override
public Image duplicate() {
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
return new BitMapWrapper(mutableBitmap);
}
/** {@inheritDoc} */
@Override
public NDArray toNDArray(NDManager manager, Flag flag) {
int[] pixels = new int[getWidth() * getHeight()];
int channel;
if (flag == Flag.GRAYSCALE) {
channel = 1;
} else {
channel = 3;
}
ByteBuffer bb = manager.allocateDirect(channel * getWidth() * getHeight());
bitmap.getPixels(pixels, 0, getWidth(), 0, 0, getWidth(), getHeight());
for (int rgb : pixels) {
int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;
if (flag == Flag.GRAYSCALE) {
int gray = (red + green + blue) / 3;
bb.put((byte) gray);
} else {
bb.put((byte) red);
bb.put((byte) green);
bb.put((byte) blue);
}
}
bb.rewind();
return manager.create(bb, new Shape(getHeight(), getWidth(), channel), DataType.UINT8);
}
/** {@inheritDoc} */
@Override
public void save(OutputStream os, String type) throws IOException {
if (!bitmap.compress(Bitmap.CompressFormat.valueOf(type.toUpperCase()), 100, os)) {
throw new IOException("Cannot save image file to output stream File type " + type);
}
}
/** {@inheritDoc} */
@Override
public List<BoundingBox> findBoundingBoxes() {
// TODO: Add grayscale conversion and use BoundFinder to implement
throw new UnsupportedOperationException("Not supported for BitMapImage");
}
/** {@inheritDoc} */
@Override
public void drawBoundingBoxes(DetectedObjects detections, float opacity) {
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
// set the paint configure
int stroke = 2;
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(stroke);
paint.setAntiAlias(true);
int imageWidth = mutableBitmap.getWidth();
int imageHeight = mutableBitmap.getHeight();
List<DetectedObjects.DetectedObject> list = detections.items();
for (DetectedObjects.DetectedObject result : list) {
String className = result.getClassName();
BoundingBox box = result.getBoundingBox();
int color = darker(randomColor());
paint.setColor(color);
Rectangle rectangle = box.getBounds();
int x = (int) (rectangle.getX() * imageWidth);
int y = (int) (rectangle.getY() * imageHeight);
canvas.drawRect(
x,
y,
x + (int) (rectangle.getWidth() * imageWidth),
y + (int) (rectangle.getHeight() * imageHeight),
paint);
drawText(canvas, color, className, x, y, stroke, 4);
// If we have a mask instead of a plain rectangle, draw tha mask
if (box instanceof Mask) {
Mask mask = (Mask) box;
drawMask(mutableBitmap, mask);
}
}
Bitmap oldBitmap = bitmap;
bitmap = mutableBitmap;
oldBitmap.recycle();
}
/** {@inheritDoc} */
@Override
public void drawRectangle(Rectangle rect, int rgb, int thickness) {
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
int color = darker(rgb);
// set the paint configure
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(thickness);
paint.setAntiAlias(true);
paint.setColor(color);
int imageWidth = mutableBitmap.getWidth();
int imageHeight = mutableBitmap.getHeight();
int x = (int) (rect.getX() * imageWidth);
int y = (int) (rect.getY() * imageHeight);
canvas.drawRect(
x,
y,
x + (int) (rect.getWidth() * imageWidth),
y + (int) (rect.getHeight() * imageHeight),
paint);
Bitmap oldBitmap = bitmap;
bitmap = mutableBitmap;
oldBitmap.recycle();
}
/** {@inheritDoc} */
@Override
public void drawMarks(List<Point> points, int radius) {
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
// set the paint configure
Paint paint = new Paint();
paint.setStrokeWidth(2);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
paint.setColor(darker(randomColor()));
for (Point point : points) {
int[][] star = createStar(point, radius);
drawPolygon(canvas, paint, star);
}
Bitmap oldBitmap = bitmap;
bitmap = mutableBitmap;
oldBitmap.recycle();
}
/** {@inheritDoc} */
@Override
public void drawJoints(Joints joints) {
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
// set the paint configure
Paint paint = new Paint();
paint.setStrokeWidth(2);
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
int imageWidth = mutableBitmap.getWidth();
int imageHeight = mutableBitmap.getHeight();
paint.setColor(darker(randomColor()));
for (Joints.Joint joint : joints.getJoints()) {
int x = (int) (joint.getX() * imageWidth);
int y = (int) (joint.getY() * imageHeight);
canvas.drawOval(x, y, x + 10, y + 10, paint);
}
Bitmap oldBitmap = bitmap;
bitmap = mutableBitmap;
oldBitmap.recycle();
}
/** {@inheritDoc} */
@Override
public void drawImage(Image overlay, boolean resize) {
if (!(overlay.getWrappedImage() instanceof Bitmap)) {
throw new IllegalArgumentException("Only Bitmap allowed");
}
if (resize) {
overlay = overlay.resize(getWidth(), getHeight(), false);
}
Bitmap target = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
canvas.drawBitmap(bitmap, 0, 0, null);
canvas.drawBitmap((Bitmap) overlay.getWrappedImage(), 0, 0, null);
Bitmap oldBitmap = bitmap;
bitmap = target;
oldBitmap.recycle();
}
private int randomColor() {
return Color.rgb(
RandomUtils.nextInt(256), RandomUtils.nextInt(256), RandomUtils.nextInt(256));
}
private int darker(int color) {
int a = Color.alpha(color);
int r = Math.round(Color.red(color) * 0.8f);
int g = Math.round(Color.green(color) * 0.8f);
int b = Math.round(Color.blue(color) * 0.8f);
return Color.argb(a, Math.min(r, 255), Math.min(g, 255), Math.min(b, 255));
}
private void drawText(
Canvas canvas, int color, String text, int x, int y, int stroke, int padding) {
Paint paint = new Paint();
Paint.FontMetrics metrics = paint.getFontMetrics();
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
paint.setAntiAlias(true);
x += stroke / 2;
y += stroke / 2;
int width = (int) (paint.measureText(text) + padding * 2 - stroke / 2);
// the height here includes ascent
int height = (int) (metrics.descent - metrics.ascent);
int ascent = (int) metrics.ascent;
Rect bounds = new Rect(x, y, x + width, y + height);
canvas.drawRect(bounds, paint);
paint.setColor(Color.WHITE);
// ascent in android is negative value, so y = y - ascent
canvas.drawText(text, x + padding, y - ascent, paint);
}
private void drawMask(Bitmap image, Mask mask) {
float r = RandomUtils.nextFloat();
float g = RandomUtils.nextFloat();
float b = RandomUtils.nextFloat();
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
int x = (int) (mask.getX() * imageWidth);
int y = (int) (mask.getY() * imageHeight);
float[][] probDist = mask.getProbDist();
// Correct some coordinates of box when going out of image
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
Bitmap maskedImage =
Bitmap.createBitmap(
probDist.length, probDist[0].length, Bitmap.Config.ARGB_8888);
for (int xCor = 0; xCor < probDist.length; xCor++) {
for (int yCor = 0; yCor < probDist[xCor].length; yCor++) {
float opacity = probDist[xCor][yCor];
if (opacity < 0.1) {
opacity = 0f;
}
if (opacity > 0.8) {
opacity = 0.8f;
}
maskedImage.setPixel(xCor, yCor, darker(Color.argb(opacity, r, g, b)));
}
}
Canvas canvas = new Canvas(image);
canvas.drawBitmap(maskedImage, x, y, null);
}
private void drawPolygon(Canvas canvas, Paint paint, int[][] polygon) {
android.graphics.Path polygonPath = new android.graphics.Path();
polygonPath.moveTo(polygon[0][0], polygon[1][0]);
for (int i = 1; i < polygon[0].length; i++) {
polygonPath.lineTo(polygon[0][i], polygon[1][i]);
}
polygonPath.close();
canvas.drawPath(polygonPath, paint);
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai
|
java-sources/ai/djl/api/0.34.0/ai/djl/Application.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl;
import java.util.Objects;
/**
* A class contains common tasks that can be completed using deep learning.
*
* <p>If you view deep learning models as being like a function, then the application is like the
* function signature. Because there are relatively few signatures used with a lot of research that
* goes into them, the common signatures are identified by a name. The application is that name.
*/
public class Application {
public static final Application UNDEFINED = new Application("undefined");
private String path;
Application(String path) {
this.path = path;
}
/**
* Returns the repository path of the application.
*
* @return the repository path of the application
*/
public String getPath() {
return path;
}
/**
* Converts a path string to a {@code Application}.
*
* @param path the repository path of the application
* @return the {@code Application}
*/
public static Application of(String path) {
switch (path) {
case "cv":
return CV.ANY;
case "cv/image_classification":
case "image_classification":
return CV.IMAGE_CLASSIFICATION;
case "cv/zero_shot_image_classification":
case "zero_shot_image_classification":
return CV.ZERO_SHOT_IMAGE_CLASSIFICATION;
case "cv/object_detection":
case "object_detection":
return CV.OBJECT_DETECTION;
case "cv/zero_shot_object_detection":
case "zero_shot_object_detection":
return CV.ZERO_SHOT_OBJECT_DETECTION;
case "cv/semantic_segmentation":
case "semantic_segmentation":
return CV.SEMANTIC_SEGMENTATION;
case "cv/instance_segmentation":
case "instance_segmentation":
return CV.INSTANCE_SEGMENTATION;
case "cv/mask_generation":
case "mask_generation":
return CV.MASK_GENERATION;
case "cv/pose_estimation":
case "pose_estimation":
return CV.POSE_ESTIMATION;
case "cv/action_recognition":
case "action_recognition":
return CV.ACTION_RECOGNITION;
case "cv/word_recognition":
case "word_recognition":
return CV.WORD_RECOGNITION;
case "cv/image_generation":
case "image_generation":
return CV.IMAGE_GENERATION;
case "cv/image_enhancement":
case "image_enhancement":
return CV.IMAGE_ENHANCEMENT;
case "nlp":
return NLP.ANY;
case "nlp/fill_mask":
case "fill_mask":
return NLP.FILL_MASK;
case "nlp/question_answer":
case "question_answering":
return NLP.QUESTION_ANSWER;
case "nlp/text_classification":
case "text_classification":
return NLP.TEXT_CLASSIFICATION;
case "nlp/sentiment_analysis":
case "sentiment_analysis":
return NLP.SENTIMENT_ANALYSIS;
case "nlp/token_classification":
case "token_classification":
return NLP.TOKEN_CLASSIFICATION;
case "nlp/zero_shot_classification":
case "zero_shot_classification":
return NLP.ZERO_SHOT_CLASSIFICATION;
case "nlp/word_embedding":
case "word_embedding":
return NLP.WORD_EMBEDDING;
case "nlp/text_generation":
case "text_generation":
return NLP.TEXT_GENERATION;
case "nlp/machine_translation":
case "machine_translation":
return NLP.MACHINE_TRANSLATION;
case "nlp/multiple_choice":
case "multiple_choice":
return NLP.MULTIPLE_CHOICE;
case "nlp/text_embedding":
case "text_embedding":
case "sentence_similarity":
return NLP.TEXT_EMBEDDING;
case "tabular":
return Tabular.ANY;
case "tabular/linear_regression":
return Tabular.LINEAR_REGRESSION;
case "tabular/softmax_regression":
return Tabular.SOFTMAX_REGRESSION;
case "audio":
return Audio.ANY;
case "timeseries/forecasting":
return TimeSeries.FORECASTING;
case "undefined":
default:
return UNDEFINED;
}
}
/** {@inheritDoc} */
@Override
public String toString() {
return path.replace('/', '.').toUpperCase();
}
/**
* Returns whether this application matches the test application set.
*
* @param test a application or application set to test against
* @return true if it fits within the application set
*/
public boolean matches(Application test) {
return path.startsWith(test.path);
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Application)) {
return false;
}
return path.equals(((Application) o).path);
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return Objects.hash(path);
}
/** The common set of applications for computer vision (image and video data). */
public interface CV {
/** Any computer vision application, including those in {@link CV}. */
Application ANY = new Application("cv");
/**
* An application where images are assigned a single class name.
*
* <p>Each image is given one of a fixed number of classes (or a probability of having that
* one class). The typical signature is Model<{@link ai.djl.modality.cv.Image}, {@link
* ai.djl.modality.Classifications}>.
*/
Application IMAGE_CLASSIFICATION = new Application("cv/image_classification");
/**
* An application where images are assigned a single class name.
*
* <p>The typical signature is Model<{@link ai.djl.modality.cv.VisionLanguageInput},
* {@link ai.djl.modality.Classifications}>.
*/
Application ZERO_SHOT_IMAGE_CLASSIFICATION =
new Application("cv/zero_shot_image_classification");
/**
* An application that finds zero or more objects in an image, the object class (see image
* classification), and their locations as a {@link ai.djl.modality.cv.output.BoundingBox}.
*
* <p>The typical signature is Model<{@link ai.djl.modality.cv.Image}, {@link
* ai.djl.modality.cv.output.DetectedObjects}>.
*
* @see <a href="https://d2l.djl.ai/chapter_computer-vision/bounding-box.html">The D2L
* chapter on object detection</a>
*/
Application OBJECT_DETECTION = new Application("cv/object_detection");
/**
* An application that finds zero or more objects in an image, the object class (see image
* classification), and their locations as a {@link ai.djl.modality.cv.output.BoundingBox}.
*
* <p>The typical signature is Model<{@link ai.djl.modality.cv.VisionLanguageInput},
* {@link ai.djl.modality.cv.output.DetectedObjects}>.
*
* @see <a href="https://d2l.djl.ai/chapter_computer-vision/bounding-box.html">The D2L
* chapter on object detection</a>
*/
Application ZERO_SHOT_OBJECT_DETECTION = new Application("cv/zero_shot_object_detection");
/** An application that classifies each pixel in an image into a category. */
Application SEMANTIC_SEGMENTATION = new Application("cv/semantic_segmentation");
/**
* An application that finds zero or more objects in an image, the object class (see image
* classification), and their location as a pixel map.
*/
Application INSTANCE_SEGMENTATION = new Application("cv/instance_segmentation");
/**
* An application that generates masks that identify a specific object or region of interest
* in a given image.
*/
Application MASK_GENERATION = new Application("cv/mask_generation");
/**
* An application that accepts an image of a single person and returns the {@link
* ai.djl.modality.cv.output.Joints} locations of the person.
*
* <p>This can often be used with {@link #OBJECT_DETECTION} to identify the people in the
* image and then run pose estimation on each detected person. The typical signature is
* Model<{@link ai.djl.modality.cv.Image}, {@link ai.djl.modality.cv.output.Joints}>.
*/
Application POSE_ESTIMATION = new Application("cv/pose_estimation");
/**
* An application that accepts an image or video and classifies the action being done in it.
*/
Application ACTION_RECOGNITION = new Application("cv/action_recognition");
/**
* An application that accepts an image of a single word and returns the {@link String} text
* of the word.
*
* <p>The typical signature is Model<{@link ai.djl.modality.cv.Image}, {@link
* String}>.
*/
Application WORD_RECOGNITION = new Application("cv/word_recognition");
/**
* An application that accepts a seed and returns generated images.
*
* <p>The typical model returns an array of images {@link ai.djl.modality.cv.Image}[].
*/
Application IMAGE_GENERATION = new Application("cv/image_generation");
/**
* An application that accepts an image and returns enhanced images.
*
* <p>The typical signature is Model<{@link ai.djl.modality.cv.Image}, {@link
* ai.djl.modality.cv.Image}>.
*/
Application IMAGE_ENHANCEMENT = new Application("cv/image_enhancement");
}
/** The common set of applications for natural language processing (text data). */
public interface NLP {
/** Any NLP application, including those in {@link NLP}. */
Application ANY = new Application("nlp");
/**
* An application that masking some words in a sentence and predicting which words should
* replace those masks.
*/
Application FILL_MASK = new Application("nlp/fill_mask");
/**
* An application that a reference document and a question about the document and returns
* text answering the question.
*
* <p>The typical signature is Model<{@link ai.djl.modality.nlp.qa.QAInput}, {@link
* String}>.
*/
Application QUESTION_ANSWER = new Application("nlp/question_answer");
/**
* An application that classifies text data.
*
* <p>The typical signature is Model<{@link String}, {@link
* ai.djl.modality.Classifications}>.
*/
Application TEXT_CLASSIFICATION = new Application("nlp/text_classification");
/**
* An application that classifies text into positive or negative, a specific case of {@link
* #TEXT_CLASSIFICATION}.
*/
Application SENTIMENT_ANALYSIS = new Application("nlp/sentiment_analysis");
/**
* An application that classifies text into arbitrary label, a specific case of {@link
* #TEXT_CLASSIFICATION}.
*/
Application ZERO_SHOT_CLASSIFICATION = new Application("nlp/zero_shot_classification");
/**
* A natural language understanding application that assigns a label to some tokens in a
* text.
*/
Application TOKEN_CLASSIFICATION = new Application("nlp/token_classification");
/**
* An application that takes a word and returns a feature vector that represents the word.
*
* <p>The most representative signature is Model<{@link String}, {@link
* ai.djl.ndarray.NDArray}>. However, many models will only embed a fixed {@link
* ai.djl.modality.nlp.Vocabulary} of words. These words are usually given integer indices
* which may make the signature Model<{@link String}, {@link ai.djl.ndarray.NDArray}>
* (or {@link ai.djl.ndarray.NDArray}). The signatures may also use singleton {@link
* ai.djl.ndarray.NDList}s instead of {@link ai.djl.ndarray.NDArray}.
*/
Application WORD_EMBEDDING = new Application("nlp/word_embedding");
Application TEXT_GENERATION = new Application("nlp/text_generation");
/**
* An application that translates text from one language to another.
*
* <p>The typical signature is Model<{@link String}, {@link String}>.
*/
Application MACHINE_TRANSLATION = new Application("nlp/machine_translation");
/** An application to represent a multiple choice question. */
Application MULTIPLE_CHOICE = new Application("nlp/multiple_choice");
/**
* An application that takes text and returns a feature vector that represents the text.
*
* <p>The special case where the text consists of only a word is a {@link #WORD_EMBEDDING}.
* The typical signature is Model<{@link String}, {@link ai.djl.ndarray.NDArray}>.
*/
Application TEXT_EMBEDDING = new Application("nlp/text_embedding");
}
/** The common set of applications for tabular data. */
public interface Tabular {
/** Any tabular application, including those in {@link Tabular}. */
Application ANY = new Application("tabular");
/**
* An application that takes a feature vector (table row) and predicts a numerical feature
* based on it.
*
* @see <a href="https://d2l.djl.ai/chapter_linear-networks/linear-regression.html">The D2L
* chapter introducing this application</a>
*/
Application LINEAR_REGRESSION = new Application("tabular/linear_regression");
/**
* An application that takes a feature vector (table row) and predicts a categorical feature
* based on it.
*
* <p>There is no typical input, but the typical output is {@link
* ai.djl.modality.Classifications}.
*
* @see <a href="https://d2l.djl.ai/chapter_linear-networks/softmax-regression.html">The D2L
* chapter introducing this application</a>
*/
Application SOFTMAX_REGRESSION = new Application("tabular/softmax_regression");
}
/** The common set of applications for audio data. */
public interface Audio {
/** Any audio application, including those in {@link Audio}. */
Application ANY = new Application("audio");
}
/** The common set of applications for timeseries extension. */
public interface TimeSeries {
/**
* An application that take a past target vector with corresponding feature and predicts a
* probability distribution based on it.
*/
Application FORECASTING = new Application("timeseries/forecasting");
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai
|
java-sources/ai/djl/api/0.34.0/ai/djl/BaseModel.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl;
import ai.djl.inference.Predictor;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.NDManager;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
import ai.djl.nn.Block;
import ai.djl.nn.SymbolBlock;
import ai.djl.training.ParameterStore;
import ai.djl.training.Trainer;
import ai.djl.training.TrainingConfig;
import ai.djl.translate.Translator;
import ai.djl.util.Pair;
import ai.djl.util.PairList;
import ai.djl.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/** {@code BaseModel} is the basic implementation of {@link Model}. */
public abstract class BaseModel implements Model {
private static final Logger logger = LoggerFactory.getLogger(BaseModel.class);
private static final int MODEL_VERSION = 1;
protected Path modelDir;
protected Block block;
protected String modelName;
protected NDManager manager;
protected DataType dataType;
protected boolean wasLoaded;
protected PairList<String, Shape> inputData;
protected Map<String, Object> artifacts = new ConcurrentHashMap<>();
protected Map<String, String> properties = new ConcurrentHashMap<>();
protected BaseModel(String modelName) {
this.modelName = modelName;
}
/** {@inheritDoc} */
@Override
public Block getBlock() {
return block;
}
/** {@inheritDoc} */
@Override
public void setBlock(Block block) {
wasLoaded = false;
this.block = block;
}
/** {@inheritDoc} */
@Override
public String getName() {
return modelName;
}
/** {@inheritDoc} */
@Override
public NDManager getNDManager() {
return manager;
}
/** {@inheritDoc} */
@Override
public Trainer newTrainer(TrainingConfig trainingConfig) {
throw new UnsupportedOperationException("Not supported!");
}
/** {@inheritDoc} */
@Override
public <I, O> Predictor<I, O> newPredictor(Translator<I, O> translator, Device device) {
return new Predictor<>(this, translator, device, false);
}
/** {@inheritDoc} */
@Override
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
/** {@inheritDoc} */
@Override
public DataType getDataType() {
return dataType;
}
/** {@inheritDoc} */
@Override
public void load(InputStream is, Map<String, ?> options)
throws IOException, MalformedModelException {
throw new UnsupportedOperationException("Not supported!");
}
/** {@inheritDoc} */
@Override
public void close() {
manager.close();
}
/** {@inheritDoc} */
@Override
public PairList<String, Shape> describeInput() {
if (inputData == null) {
inputData = block.describeInput();
}
return inputData;
}
/** {@inheritDoc} */
@Override
public PairList<String, Shape> describeOutput() {
if (block instanceof SymbolBlock) {
return ((SymbolBlock) block).describeOutput();
}
// create fake input to calculate output shapes
NDList input = new NDList();
for (Pair<String, Shape> pair : describeInput()) {
input.add(manager.ones(pair.getValue()));
}
List<String> outputNames = new ArrayList<>();
NDList output = block.forward(new ParameterStore(manager, true), input, false);
Shape[] outputShapes = output.stream().map(NDArray::getShape).toArray(Shape[]::new);
for (int i = 0; i < outputShapes.length; i++) {
outputNames.add("output" + i);
}
return new PairList<>(outputNames, Arrays.asList(outputShapes));
}
/** {@inheritDoc} */
@Override
public String[] getArtifactNames() {
throw new UnsupportedOperationException("Not supported!");
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
public <T> T getArtifact(String name, Function<InputStream, T> function) throws IOException {
try {
Object artifact =
artifacts.computeIfAbsent(
name,
v -> {
try (InputStream is = getArtifactAsStream(name)) {
return function.apply(is);
} catch (IOException e) {
throw new IllegalStateException(e);
}
});
return (T) artifact;
} catch (RuntimeException e) {
Throwable t = e.getCause();
if (t instanceof IOException) {
throw (IOException) e.getCause();
}
throw e;
}
}
/** {@inheritDoc} */
@Override
public URL getArtifact(String artifactName) throws IOException {
if (artifactName == null) {
throw new IllegalArgumentException("artifactName cannot be null");
}
Path file = modelDir.resolve(artifactName);
if (Files.exists(file) && Files.isReadable(file)) {
return file.toUri().toURL();
}
throw new FileNotFoundException("File not found: " + file);
}
/** {@inheritDoc} */
@Override
public InputStream getArtifactAsStream(String name) throws IOException {
URL url = getArtifact(name);
return new BufferedInputStream(url.openStream());
}
/** {@inheritDoc} */
@Override
public void setProperty(String key, String value) {
properties.put(key, value);
}
/** {@inheritDoc} */
@Override
public String getProperty(String key) {
return properties.get(key);
}
/** {@inheritDoc} */
@Override
public Map<String, String> getProperties() {
return properties;
}
protected void setModelDir(Path modelDir) {
this.modelDir = Utils.getNestedModelDir(modelDir);
}
protected void loadBlock(String prefix, Map<String, ?> options)
throws IOException, MalformedModelException {
boolean hasParameter = true;
if (options != null) {
String paramOption = (String) options.get("hasParameter");
if (paramOption != null) {
hasParameter = Boolean.parseBoolean(paramOption);
}
}
if (hasParameter) {
Path paramFile = paramPathResolver(prefix, options);
if (paramFile == null) {
throw new IOException(
"Parameter file not found in: "
+ modelDir
+ ". If you only specified model path, make sure path name"
+ " match your saved model file name.");
}
readParameters(paramFile, options);
}
}
/** {@inheritDoc} */
@Override
public void save(Path modelPath, String newModelName) throws IOException {
if (newModelName == null || newModelName.isEmpty()) {
newModelName = modelName;
}
if (Files.notExists(modelPath)) {
Files.createDirectories(modelPath);
}
if (block == null || !block.isInitialized()) {
throw new IllegalStateException("Model has not be trained or loaded yet.");
}
String epochValue = getProperty("Epoch");
int epoch =
epochValue == null
? Utils.getCurrentEpoch(modelPath, newModelName) + 1
: Integer.parseInt(epochValue);
String fileName = String.format(Locale.ROOT, "%s-%04d.params", newModelName, epoch);
Path paramFile = modelPath.resolve(fileName);
try (DataOutputStream dos =
new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(paramFile)))) {
dos.writeBytes("DJL@");
dos.writeInt(MODEL_VERSION);
dos.writeUTF(newModelName);
dos.writeUTF(dataType.name());
inputData = block.describeInput();
dos.writeInt(inputData.size());
for (Pair<String, Shape> desc : inputData) {
String name = desc.getKey();
if (name == null) {
dos.writeUTF("");
} else {
dos.writeUTF(name);
}
dos.write(desc.getValue().getEncoded());
}
dos.writeInt(properties.size());
for (Map.Entry<String, String> entry : properties.entrySet()) {
dos.writeUTF(entry.getKey());
dos.writeUTF(entry.getValue());
}
block.saveParameters(dos);
}
modelDir = modelPath.toAbsolutePath();
}
/** {@inheritDoc} */
@Override
public Path getModelPath() {
return modelDir;
}
/** {@inheritDoc} */
@Override
public String toString() {
StringBuilder sb = new StringBuilder(200);
sb.append("Model (\n\tName: ").append(modelName);
if (modelDir != null) {
sb.append("\n\tModel location: ").append(modelDir.toAbsolutePath());
}
sb.append("\n\tData Type: ").append(dataType);
for (Map.Entry<String, String> entry : properties.entrySet()) {
sb.append("\n\t").append(entry.getKey()).append(": ").append(entry.getValue());
}
sb.append("\n)");
return sb.toString();
}
/** {@inheritDoc} */
@SuppressWarnings("deprecation")
@Override
protected void finalize() throws Throwable {
if (manager.isOpen()) {
logger.warn("Model: {} was not closed explicitly.", modelName);
manager.close();
}
super.finalize();
}
protected Path paramPathResolver(String prefix, Map<String, ?> options) throws IOException {
Object epochOption = null;
if (options != null) {
epochOption = options.get("epoch");
}
int epoch;
if (epochOption == null) {
epoch = Utils.getCurrentEpoch(modelDir, prefix);
if (epoch == -1) {
return null;
}
} else {
epoch = Integer.parseInt(epochOption.toString());
}
return modelDir.resolve(String.format(Locale.ROOT, "%s-%04d.params", prefix, epoch));
}
protected boolean readParameters(Path paramFile, Map<String, ?> options)
throws IOException, MalformedModelException {
logger.debug("Try to load model from {}", paramFile);
return readParameters(Files.newInputStream(paramFile), options);
}
protected boolean readParameters(InputStream paramStream, Map<String, ?> options)
throws IOException, MalformedModelException {
try (DataInputStream dis = new DataInputStream(new BufferedInputStream(paramStream))) {
byte[] buf = new byte[4];
dis.readFully(buf);
if (!"DJL@".equals(new String(buf, StandardCharsets.US_ASCII))) {
return false;
}
int version = dis.readInt();
if (version != MODEL_VERSION) {
throw new IOException("Unsupported model version: " + version);
}
String savedModelName = dis.readUTF();
logger.debug("Loading saved model: {} parameter", savedModelName);
dataType = DataType.valueOf(dis.readUTF());
int numberOfInputs = dis.readInt();
inputData = new PairList<>();
for (int i = 0; i < numberOfInputs; ++i) {
String inputName = dis.readUTF(); // input name
Shape shape = Shape.decode(dis);
inputData.add(inputName, shape);
}
int numberOfProperties = dis.readInt();
for (int i = 0; i < numberOfProperties; ++i) {
String key = dis.readUTF();
String value = dis.readUTF();
properties.put(key, value);
}
block.loadParameters(manager, dis);
logger.debug("DJL model loaded successfully");
}
return true;
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai
|
java-sources/ai/djl/api/0.34.0/ai/djl/Device.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl;
import ai.djl.engine.Engine;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* The {@code Device} class provides the specified assignment for CPU/GPU processing on the {@code
* NDArray}.
*
* <p>Users can use this to specify whether to load/compute the {@code NDArray} on CPU/GPU with
* deviceType and deviceId provided.
*
* @see <a href="https://d2l.djl.ai/chapter_deep-learning-computation/use-gpu.html">The D2L chapter
* on GPU devices</a>
*/
public class Device {
private static final Map<String, Device> CACHE = new ConcurrentHashMap<>();
private static final Device CPU = new Device(Type.CPU, -1);
private static final Device GPU = Device.of(Type.GPU, 0);
private static final Pattern DEVICE_NAME = Pattern.compile("([a-z]+)([0-9]*)");
protected String deviceType;
protected int deviceId;
/**
* Creates a {@code Device} with basic information.
*
* @param deviceType the device type, typically CPU or GPU
* @param deviceId the deviceId on the hardware. For example, if you have multiple GPUs, you can
* choose which GPU to process the NDArray
*/
private Device(String deviceType, int deviceId) {
this.deviceType = deviceType;
this.deviceId = deviceId;
}
/**
* Returns a {@code Device} with device type and device id.
*
* @param deviceType the device type, typically CPU or GPU
* @param deviceId the deviceId on the hardware.
* @return a {@code Device} instance
*/
public static Device of(String deviceType, int deviceId) {
if (Type.CPU.equals(deviceType)) {
return CPU;
}
String key = deviceType + '-' + deviceId;
return CACHE.computeIfAbsent(key, k -> new Device(deviceType, deviceId));
}
/**
* Parses a deviceName string into a device for the default engine.
*
* @param deviceName deviceName String to parse
* @return the parsed device
* @see #fromName(String, Engine)
*/
public static Device fromName(String deviceName) {
return fromName(deviceName, Engine.getInstance());
}
/**
* Parses a deviceName string into a device.
*
* <p>The main format of a device name string is "cpu", "gpu0", or "nc1". This is simply
* deviceType concatenated with the deviceId. If no deviceId is used, -1 will be assumed.
*
* <p>There are also several simplified formats. The "-1", deviceNames corresponds to cpu.
* Non-negative integer deviceNames such as "0", "1", or "2" correspond to gpus with those
* deviceIds.
*
* <p>Finally, unspecified deviceNames (null or "") are parsed into the engine's default device.
*
* @param deviceName deviceName string
* @param engine the engine the devie is for
* @return the device
*/
public static Device fromName(String deviceName, Engine engine) {
if (deviceName == null || deviceName.isEmpty()) {
return engine.defaultDevice();
}
if (deviceName.contains("+")) {
String[] split = deviceName.split("\\+");
List<Device> subDevices =
Arrays.stream(split).map(n -> fromName(n, engine)).collect(Collectors.toList());
return new MultiDevice(subDevices);
}
Matcher matcher = DEVICE_NAME.matcher(deviceName);
if (matcher.matches()) {
String deviceType = matcher.group(1);
int deviceId = -1;
if (!matcher.group(2).isEmpty()) {
deviceId = Integer.parseInt(matcher.group(2));
}
return Device.of(deviceType, deviceId);
}
try {
int deviceId = Integer.parseInt(deviceName);
if (deviceId < 0) {
return Device.cpu();
}
return Device.gpu(deviceId);
} catch (NumberFormatException ignored) {
}
throw new IllegalArgumentException("Failed to parse device name: " + deviceName);
}
/**
* Returns the device type of the Device.
*
* @return the device type of the Device
*/
public String getDeviceType() {
return deviceType;
}
/**
* Returns the {@code deviceId} of the Device.
*
* @return the {@code deviceId} of the Device
*/
public int getDeviceId() {
return deviceId;
}
/**
* Returns if the {@code Device} is GPU.
*
* @return if the {@code Device} is GPU.
*/
public boolean isGpu() {
return Type.GPU.equals(deviceType);
}
/**
* Returns the sub devices if present (such as a {@link MultiDevice}), otherwise this.
*
* @return the sub devices if present (such as a {@link MultiDevice}), otherwise this.
*/
public List<Device> getDevices() {
return Collections.singletonList(this);
}
/** {@inheritDoc} */
@Override
public String toString() {
if (Type.CPU.equals(deviceType)) {
return deviceType + "()";
}
return deviceType + '(' + deviceId + ')';
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Device device = (Device) o;
if (Type.CPU.equals(deviceType)) {
return Objects.equals(deviceType, device.deviceType);
}
return deviceId == device.deviceId && Objects.equals(deviceType, device.deviceType);
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return Objects.hash(deviceType, deviceId);
}
/**
* Returns the default CPU Device.
*
* @return the default CPU Device
*/
public static Device cpu() {
return CPU;
}
/**
* Returns the default GPU Device.
*
* @return the default GPU Device
*/
public static Device gpu() {
return GPU;
}
/**
* Returns a new instance of GPU {@code Device} with the specified {@code deviceId}.
*
* @param deviceId the GPU device ID
* @return a new instance of GPU {@code Device} with specified {@code deviceId}
*/
public static Device gpu(int deviceId) {
return of(Type.GPU, deviceId);
}
/** Contains device type string constants. */
public interface Type {
String CPU = "cpu";
String GPU = "gpu";
}
/** A combined {@link Device} representing the composition of multiple other devices. */
public static class MultiDevice extends Device {
List<Device> devices;
/**
* Constructs a {@link MultiDevice} with a range of new devices.
*
* @param deviceType the type of the sub-devices
* @param startInclusive the start (inclusive) of the devices range
* @param endExclusive the end (exclusive) of the devices range
*/
public MultiDevice(String deviceType, int startInclusive, int endExclusive) {
this(
IntStream.range(startInclusive, endExclusive)
.mapToObj(i -> Device.of(deviceType, i))
.collect(Collectors.toList()));
}
/**
* Constructs a {@link MultiDevice} from sub devices.
*
* @param devices the sub devices
*/
public MultiDevice(Device... devices) {
this(Arrays.asList(devices));
}
/**
* Constructs a {@link MultiDevice} from sub devices.
*
* @param devices the sub devices
*/
public MultiDevice(List<Device> devices) {
super(null, -1);
devices.sort(
Comparator.comparing(Device::getDeviceType, String.CASE_INSENSITIVE_ORDER)
.thenComparingInt(Device::getDeviceId));
this.deviceType =
String.join(
"+",
(Iterable<String>)
() ->
devices.stream()
.map(d -> d.getDeviceType() + d.getDeviceId())
.iterator());
this.devices = devices;
}
/** {@inheritDoc} */
@Override
public List<Device> getDevices() {
return devices;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
MultiDevice that = (MultiDevice) o;
return Objects.equals(devices, that.devices);
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), devices);
}
/** {@inheritDoc} */
@Override
public String toString() {
return deviceType + "()";
}
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai
|
java-sources/ai/djl/api/0.34.0/ai/djl/MalformedModelException.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl;
/** Thrown to indicate Model parameters are not in expected format or are malformed. */
public class MalformedModelException extends ModelException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new exception with the specified detail message. The cause is not initialized,
* and may subsequently be initialized by a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for later retrieval by the
* {@link #getMessage()} method.
*/
public MalformedModelException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* <p>Note that the detail message associated with {@code cause} is <i>not</i> automatically
* incorporated in this exception's detail message.
*
* @param message the detail message that is saved for later retrieval by the {@link
* #getMessage()} method
* @param cause the cause that is saved for later retrieval by the {@link #getCause()} method. A
* {@code null} value is permitted, and indicates that the cause is nonexistent or unknown
*/
public MalformedModelException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause and a detail message of {@code
* (cause==null ? null : cause.toString())} which typically contains the class and detail
* message of {@code cause}. This constructor is useful for exceptions that are little more than
* wrappers for other throwables. For example, {@link java.security.PrivilegedActionException}.
*
* @param cause the cause that is saved for later retrieval by the {@link #getCause()} method. A
* {@code null} value is permitted, and indicates that the cause is nonexistent or unknown
*/
public MalformedModelException(Throwable cause) {
super(cause);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai
|
java-sources/ai/djl/api/0.34.0/ai/djl/Model.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl;
import ai.djl.engine.Engine;
import ai.djl.inference.Predictor;
import ai.djl.ndarray.NDManager;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
import ai.djl.nn.Block;
import ai.djl.training.Trainer;
import ai.djl.training.TrainingConfig;
import ai.djl.translate.Translator;
import ai.djl.util.PairList;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Path;
import java.util.Map;
import java.util.function.Function;
/**
* A model is a collection of artifacts that is created by the training process.
*
* <p>A deep learning model usually contains the following parts:
*
* <ul>
* <li>the {@link Block} of operations to run
* <li>the {@link ai.djl.nn.Parameter}s that are trained
* <li>Input/Output information: input and output parameter names, shape, etc.
* <li>Other artifacts such as a synset for classification that would be used during
* pre-processing and post-processing
* </ul>
*
* <p>For loading a pre-trained model, see {@link Model#load(Path, String)}
*
* <p>For training a model, see {@link Trainer}.
*
* <p>For running inference with a model, see {@link Predictor}.
*/
public interface Model extends AutoCloseable {
/**
* Creates an empty model instance.
*
* @param name the model name
* @return a new Model instance
*/
static Model newInstance(String name) {
return newInstance(name, (Device) null);
}
/**
* Creates an empty model instance on the specified {@link Device}.
*
* @param name the model name
* @param device the device to load the model onto
* @return a new model instance
*/
static Model newInstance(String name, Device device) {
return Engine.getInstance().newModel(name, device);
}
/**
* Creates an empty model instance on the specified {@link Device} and engine.
*
* @param name the model name
* @param engineName the name of the engine
* @return a new model instance
*/
static Model newInstance(String name, String engineName) {
Engine engine = Engine.getEngine(engineName);
return engine.newModel(name, null);
}
/**
* Creates an empty model instance on the specified {@link Device} and engine.
*
* @param name the model name
* @param device the device to load the model onto
* @param engineName the name of the engine
* @return a new model instance
*/
static Model newInstance(String name, Device device, String engineName) {
if (engineName == null || engineName.isEmpty()) {
return newInstance(name, device);
}
return Engine.getEngine(engineName).newModel(name, device);
}
/**
* Loads the model from the {@code modelPath}.
*
* @param modelPath the directory or file path of the model location
* @throws IOException when IO operation fails in loading a resource
* @throws MalformedModelException if model file is corrupted
*/
default void load(Path modelPath) throws IOException, MalformedModelException {
load(modelPath, null, null);
}
/**
* Loads the model from the {@code modelPath} and the given name.
*
* @param modelPath the directory or file path of the model location
* @param prefix the model file name or path prefix
* @throws IOException when IO operation fails in loading a resource
* @throws MalformedModelException if model file is corrupted
*/
default void load(Path modelPath, String prefix) throws IOException, MalformedModelException {
load(modelPath, prefix, null);
}
/**
* Loads the model from the {@code modelPath} with the name and options provided.
*
* @param modelPath the directory or file path of the model location
* @param prefix the model file name or path prefix
* @param options engine specific load model options, see documentation for each engine
* @throws IOException when IO operation fails in loading a resource
* @throws MalformedModelException if model file is corrupted
*/
void load(Path modelPath, String prefix, Map<String, ?> options)
throws IOException, MalformedModelException;
/**
* Loads the model from the {@code InputStream}.
*
* @param is the {@code InputStream} to load the model from
* @throws IOException when IO operation fails in loading a resource
* @throws MalformedModelException if model file is corrupted
*/
default void load(InputStream is) throws IOException, MalformedModelException {
load(is, null);
}
/**
* Loads the model from the {@code InputStream} with the options provided.
*
* @param is the {@code InputStream} to load the model from
* @param options engine specific load model options, see documentation for each engine
* @throws IOException when IO operation fails in loading a resource
* @throws MalformedModelException if model file is corrupted
*/
void load(InputStream is, Map<String, ?> options) throws IOException, MalformedModelException;
/**
* Saves the model to the specified {@code modelPath} with the name provided.
*
* @param modelPath the directory or file path of the model location
* @param newModelName the new model name to be saved, use null to keep original model name
* @throws IOException when IO operation fails in loading a resource
*/
void save(Path modelPath, String newModelName) throws IOException;
/**
* Returns the directory from where the model is loaded.
*
* @return the directory of the model location
*/
Path getModelPath();
/**
* Gets the block from the Model.
*
* @return the {@link Block}
*/
Block getBlock();
/**
* Sets the block for the Model for training and inference.
*
* @param block the {@link Block} used in Model
*/
void setBlock(Block block);
/**
* Gets the model name.
*
* @return name of the model
*/
String getName();
/**
* Returns the model's properties.
*
* @return the model's properties
*/
Map<String, String> getProperties();
/**
* Returns the property of the model based on property name.
*
* @param key the name of the property
* @return the value of the property
*/
String getProperty(String key);
/**
* Returns the property of the model based on property name.
*
* @param key the name of the property
* @param defValue the default value if key not found
* @return the value of the property
*/
default String getProperty(String key, String defValue) {
String value = getProperty(key);
if (value == null || value.isEmpty()) {
return defValue;
}
return value;
}
/**
* Sets a property to the model.
*
* <p>properties will be saved/loaded with model, user can store some information about the
* model in here.
*
* @param key the name of the property
* @param value the value of the property
*/
void setProperty(String key, String value);
/**
* Returns the property of the model based on property name.
*
* @param key the name of the property
* @param defValue the default value if key not found
* @return the value of the property
*/
default int intProperty(String key, int defValue) {
String value = getProperty(key);
if (value == null || value.isEmpty()) {
return defValue;
}
return Integer.parseInt(value);
}
/**
* Returns the property of the model based on property name.
*
* @param key the name of the property
* @param defValue the default value if key not found
* @return the value of the property
*/
default long longProperty(String key, long defValue) {
String value = getProperty(key);
if (value == null || value.isEmpty()) {
return defValue;
}
return Integer.parseInt(value);
}
/**
* Gets the {@link NDManager} from the model.
*
* @return the {@link NDManager}
*/
NDManager getNDManager();
/**
* Creates a new {@link Trainer} instance for a Model.
*
* @param trainingConfig training configuration settings
* @return the {@link Trainer} instance
*/
Trainer newTrainer(TrainingConfig trainingConfig);
/**
* Creates a new Predictor based on the model on the current device.
*
* @param translator the object used for pre-processing and postprocessing
* @param <I> the input object for pre-processing
* @param <O> the output object from postprocessing
* @return an instance of {@code Predictor}
*/
default <I, O> Predictor<I, O> newPredictor(Translator<I, O> translator) {
return newPredictor(translator, getNDManager().getDevice());
}
/**
* Creates a new Predictor based on the model.
*
* @param translator the object used for pre-processing and postprocessing
* @param device the device to use for prediction
* @param <I> the input object for pre-processing
* @param <O> the output object from postprocessing
* @return an instance of {@code Predictor}
*/
<I, O> Predictor<I, O> newPredictor(Translator<I, O> translator, Device device);
/**
* Returns the input descriptor of the model.
*
* <p>It contains the information that can be extracted from the model, usually name, shape,
* layout and DataType.
*
* @return a PairList of String and Shape
*/
PairList<String, Shape> describeInput();
/**
* Returns the output descriptor of the model.
*
* <p>It contains the output information that can be obtained from the model.
*
* @return a PairList of String and Shape
*/
PairList<String, Shape> describeOutput();
/**
* Returns the artifact names associated with the model.
*
* @return an array of artifact names
*/
String[] getArtifactNames();
/**
* Attempts to load the artifact using the given function and cache it if the specified artifact
* is not already cached.
*
* <p>Model will cache loaded artifact, so the user doesn't need to keep tracking it.
*
* <pre>{@code
* String synset = model.getArtifact("synset.txt", k -> IOUtils.toString(k)));
* }</pre>
*
* @param name the name of the desired artifact
* @param function the function to load the artifact
* @param <T> the type of the returned artifact object
* @return the current (existing or computed) artifact associated with the specified name, or
* null if the computed value is null
* @throws IOException when IO operation fails in loading a resource
* @throws ClassCastException if the cached artifact cannot be cast to the target class
*/
<T> T getArtifact(String name, Function<InputStream, T> function) throws IOException;
/**
* Finds an artifact resource with a given name in the model.
*
* @param name the name of the desired artifact
* @return a {@link java.net.URL} object or {@code null} if no artifact with this name is found
* @throws IOException when IO operation fails in loading a resource
*/
URL getArtifact(String name) throws IOException;
/**
* Finds an artifact resource with a given name in the model.
*
* @param name the name of the desired artifact
* @return a {@link java.io.InputStream} object or {@code null} if no resource with this name is
* found
* @throws IOException when IO operation fails in loading a resource
*/
InputStream getArtifactAsStream(String name) throws IOException;
/**
* Sets the standard data type used within the model.
*
* @param dataType the standard data type to use
*/
void setDataType(DataType dataType);
/**
* Returns the standard data type used within the model.
*
* @return the standard data type used within the model
*/
DataType getDataType();
/**
* Casts the model to support a different precision level.
*
* <p>For example, you can cast the precision from Float to Int
*
* @param dataType the target dataType you would like to cast to
*/
default void cast(DataType dataType) {
throw new UnsupportedOperationException("Not implemented yet");
}
/**
* Converts the model to use a lower precision quantized network.
*
* <p>Quantization converts the network to use int8 data type where possible for smaller model
* size and faster computation without too large a drop in accuracy. See <a
* href="https://arxiv.org/abs/1412.6115">original paper</a>.
*/
default void quantize() {
throw new UnsupportedOperationException("Not implemented yet");
}
/** {@inheritDoc} */
@Override
void close();
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai
|
java-sources/ai/djl/api/0.34.0/ai/djl/ModelException.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl;
/** Thrown to indicate Model parameter or load exceptions parent to Model Exceptions. */
public class ModelException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Constructs a new exception with the specified detail message. The cause is not initialized,
* and may subsequently be initialized by a call to {@link #initCause}.
*
* @param message the detail message that is saved for later retrieval by the {@link
* #getMessage()} method
*/
public ModelException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* <p>Note that the detail message associated with {@code cause} is <i>not</i> automatically
* incorporated in this exception's detail message.
*
* @param message the detail message that is saved for later retrieval by the {@link
* #getMessage()} method
* @param cause the cause that is saved for later retrieval by the {@link #getCause()} method. A
* {@code null} value is permitted, and indicates that the cause is nonexistent or unknown
*/
public ModelException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause and a detail message of {@code
* (cause==null ? null : cause.toString())} which typically contains the class and detail
* message of {@code cause}. This constructor is useful for exceptions that are little more than
* wrappers for other throwables. For example, {@link java.security.PrivilegedActionException}.
*
* @param cause the cause that is saved for later retrieval by the {@link #getCause()} method. A
* {@code null} value is permitted, and indicates that the cause is nonexistent or unknown
*/
public ModelException(Throwable cause) {
super(cause);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai
|
java-sources/ai/djl/api/0.34.0/ai/djl/TrainingDivergedException.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl;
/**
* Thrown to indicate when there is a divergence during Training. For eg: NaNs in Loss after an
* epoch.
*/
public class TrainingDivergedException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new exception with the specified detail message. The cause is not initialized,
* and may subsequently be initialized by a call to {@link #initCause}.
*
* @param message the detail message that is saved for later retrieval by the {@link
* #getMessage()} method
*/
public TrainingDivergedException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* <p>Note that the detail message associated with {@code cause} is <i>not</i> automatically
* incorporated in this exception's detail message.
*
* @param message the detail message that is saved for later retrieval by the {@link
* #getMessage()} method
* @param cause the cause that is saved for later retrieval by the {@link #getCause()} method. A
* {@code null} value is permitted, and indicates that the cause is nonexistent or unknown
*/
public TrainingDivergedException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause and a detail message of {@code
* (cause==null ? null : cause.toString())} which typically contains the class and detail
* message of {@code cause}. This constructor is useful for exceptions that are little more than
* wrappers for other throwables. For example, {@link java.security.PrivilegedActionException}.
*
* @param cause the cause that is saved for later retrieval by the {@link #getCause()} method. A
* {@code null} value is permitted, and indicates that the cause is nonexistent or unknown
*/
public TrainingDivergedException(Throwable cause) {
super(cause);
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai
|
java-sources/ai/djl/api/0.34.0/ai/djl/package-info.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* Contains top level, engine-agnostic classes for both inference and training.
*
* @see ai.djl.Model
* @see ai.djl.Device
*/
package ai.djl;
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/Engine.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl.engine;
import ai.djl.Device;
import ai.djl.Model;
import ai.djl.ndarray.NDManager;
import ai.djl.nn.SymbolBlock;
import ai.djl.training.GradientCollector;
import ai.djl.training.LocalParameterServer;
import ai.djl.training.ParameterServer;
import ai.djl.training.optimizer.Optimizer;
import ai.djl.util.Ec2Utils;
import ai.djl.util.RandomUtils;
import ai.djl.util.Utils;
import ai.djl.util.cuda.CudaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.MemoryUsage;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
/**
* The {@code Engine} interface is the base of the provided implementation for DJL.
*
* <p>Any engine-specific functionality should be provided through this class. In general, it should
* contain methods to detect information about the usable machine hardware and to create a new
* {@link NDManager} and {@link Model}.
*
* @see <a href="https://docs.djl.ai/master/docs/engine.html">Engine Guide</a>
* @see EngineProvider
* @see <a href="https://docs.djl.ai/master/docs/development/cache_management.html">The guide on
* resource and engine caching</a>
*/
public abstract class Engine {
private static final Logger logger = LoggerFactory.getLogger(Engine.class);
private static final Map<String, EngineProvider> ALL_ENGINES = new ConcurrentHashMap<>();
private static final String DEFAULT_ENGINE = initEngine();
private static final Pattern PATTERN =
Pattern.compile("KEY|TOKEN|PASSWORD", Pattern.CASE_INSENSITIVE);
private Device defaultDevice;
// use object to check if it's set
private Integer seed;
private static synchronized String initEngine() {
ServiceLoader<EngineProvider> loaders = ServiceLoader.load(EngineProvider.class);
for (EngineProvider provider : loaders) {
registerEngine(provider);
}
if (ALL_ENGINES.isEmpty()) {
logger.debug("No engine found from EngineProvider");
return null;
}
String def = System.getProperty("ai.djl.default_engine");
String defaultEngine = Utils.getenv("DJL_DEFAULT_ENGINE", def);
boolean aarch64 = "aarch64".equals(System.getProperty("os.arch"));
if (defaultEngine == null || defaultEngine.isEmpty()) {
int rank = Integer.MAX_VALUE;
for (EngineProvider provider : ALL_ENGINES.values()) {
if (aarch64 && "MXNet".equals(provider.getEngineName())) {
// exclude MXNet on aarch64 machine
continue;
}
if (provider.getEngineRank() < rank) {
defaultEngine = provider.getEngineName();
rank = provider.getEngineRank();
}
}
} else if (!ALL_ENGINES.containsKey(defaultEngine)) {
throw new EngineException("Unknown default engine: " + defaultEngine);
}
logger.debug("Found default engine: {}", defaultEngine);
Ec2Utils.callHome(defaultEngine);
return defaultEngine;
}
/**
* Returns the alternative {@code engine} if available.
*
* @return the alternative {@code engine}
*/
public abstract Engine getAlternativeEngine();
/**
* Returns the name of the Engine.
*
* @return the name of the engine
*/
public abstract String getEngineName();
/**
* Return the rank of the {@code Engine}.
*
* @return the rank of the engine
*/
public abstract int getRank();
/**
* Returns the default Engine name.
*
* @return the default Engine name
*/
public static String getDefaultEngineName() {
return System.getProperty("ai.djl.default_engine", DEFAULT_ENGINE);
}
/**
* Returns the default Engine.
*
* @return the instance of {@code Engine}
* @see EngineProvider
*/
public static Engine getInstance() {
if (DEFAULT_ENGINE == null) {
throw new EngineException(
"No deep learning engine found."
+ System.lineSeparator()
+ "Please refer to"
+ " https://github.com/deepjavalibrary/djl/blob/master/docs/development/troubleshooting.md"
+ " for more details.");
}
return getEngine(getDefaultEngineName());
}
/**
* Returns if the specified engine is available.
*
* @param engineName the name of Engine to check
* @return {@code true} if the specified engine is available
* @see EngineProvider
*/
public static boolean hasEngine(String engineName) {
return ALL_ENGINES.containsKey(engineName);
}
/**
* Registers a {@link EngineProvider} if not registered.
*
* @param provider the {@code EngineProvider} to be registered
*/
public static void registerEngine(EngineProvider provider) {
logger.debug("Registering EngineProvider: {}", provider.getEngineName());
ALL_ENGINES.putIfAbsent(provider.getEngineName(), provider);
}
/**
* Returns a set of engine names that are loaded.
*
* @return a set of engine names that are loaded
*/
public static Set<String> getAllEngines() {
return ALL_ENGINES.keySet();
}
/**
* Returns the {@code Engine} with the given name.
*
* @param engineName the name of Engine to retrieve
* @return the instance of {@code Engine}
* @see EngineProvider
*/
public static Engine getEngine(String engineName) {
EngineProvider provider = ALL_ENGINES.get(engineName);
if (provider == null) {
throw new IllegalArgumentException("Deep learning engine not found: " + engineName);
}
return provider.getEngine();
}
/**
* Returns the version of the deep learning engine.
*
* @return the version number of the deep learning engine
*/
public abstract String getVersion();
/**
* Returns whether the engine has the specified capability.
*
* @param capability the capability to retrieve
* @return {@code true} if the engine has the specified capability
*/
public abstract boolean hasCapability(String capability);
/**
* Returns the engine's default {@link Device}.
*
* @return the engine's default {@link Device}
*/
public Device defaultDevice() {
if (defaultDevice == null) {
if (hasCapability(StandardCapabilities.CUDA) && CudaUtils.getGpuCount() > 0) {
defaultDevice = Device.gpu();
} else {
defaultDevice = Device.cpu();
}
}
return defaultDevice;
}
/**
* Returns an array of devices.
*
* <p>If GPUs are available, it will return an array of {@code Device} of size
* \(min(numAvailable, maxGpus)\). Else, it will return an array with a single CPU device.
*
* @return an array of devices
*/
public Device[] getDevices() {
return getDevices(Integer.MAX_VALUE);
}
/**
* Returns an array of devices given the maximum number of GPUs to use.
*
* <p>If GPUs are available, it will return an array of {@code Device} of size
* \(min(numAvailable, maxGpus)\). Else, it will return an array with a single CPU device.
*
* @param maxGpus the max number of GPUs to use. Use 0 for no GPUs.
* @return an array of devices
*/
public Device[] getDevices(int maxGpus) {
int count = getGpuCount();
if (maxGpus <= 0 || count <= 0) {
return new Device[] {Device.cpu()};
}
count = Math.min(maxGpus, count);
Device[] devices = new Device[count];
for (int i = 0; i < count; ++i) {
devices[i] = Device.gpu(i);
}
return devices;
}
/**
* Returns the number of GPUs available in the system.
*
* @return the number of GPUs available in the system
*/
public int getGpuCount() {
if (hasCapability(StandardCapabilities.CUDA)) {
return CudaUtils.getGpuCount();
}
return 0;
}
/**
* Construct an empty SymbolBlock for loading.
*
* @param manager the manager to manage parameters
* @return Empty {@link SymbolBlock} for static graph
*/
public SymbolBlock newSymbolBlock(NDManager manager) {
throw new UnsupportedOperationException("Not supported.");
}
/**
* Constructs a new model.
*
* @param name the model name
* @param device the device that the model will be loaded onto
* @return a new Model instance using the network defined in block
*/
public abstract Model newModel(String name, Device device);
/**
* Creates a new top-level {@link NDManager}.
*
* <p>{@code NDManager} will inherit default {@link Device}.
*
* @return a new top-level {@code NDManager}
*/
public abstract NDManager newBaseManager();
/**
* Creates a new top-level {@link NDManager} with specified {@link Device}.
*
* @param device the default {@link Device}
* @return a new top-level {@code NDManager}
*/
public abstract NDManager newBaseManager(Device device);
/**
* Returns a new instance of {@link GradientCollector}.
*
* @return a new instance of {@link GradientCollector}
*/
public GradientCollector newGradientCollector() {
throw new UnsupportedOperationException("Not supported.");
}
/**
* Returns a new instance of {@link ParameterServer}.
*
* @param optimizer the optimizer to update
* @return a new instance of {@link ParameterServer}
*/
public ParameterServer newParameterServer(Optimizer optimizer) {
return new LocalParameterServer(optimizer);
}
/**
* Seeds the random number generator in DJL Engine.
*
* <p>This will affect all {@link Device}s and all operators using Engine's random number
* generator.
*
* @param seed the seed to be fixed in Engine
*/
public void setRandomSeed(int seed) {
this.seed = seed;
RandomUtils.RANDOM.setSeed(seed);
}
/**
* Returns the random seed in DJL Engine.
*
* @return seed the seed to be fixed in Engine
*/
public Integer getSeed() {
return seed;
}
/**
* Returns the DJL API version.
*
* @return seed the seed to be fixed in Engine
*/
public static String getDjlVersion() {
String version = Engine.class.getPackage().getSpecificationVersion();
if (version != null) {
return version;
}
try (InputStream is = Engine.class.getResourceAsStream("api.properties")) {
Properties prop = new Properties();
prop.load(is);
return prop.getProperty("djl_version");
} catch (IOException e) {
throw new AssertionError("Failed to open api.properties", e);
}
}
/** {@inheritDoc} */
@Override
public String toString() {
return getEngineName() + ':' + getVersion();
}
/** Prints debug information about the environment for debugging environment issues. */
@SuppressWarnings("PMD.SystemPrintln")
public static void debugEnvironment() {
System.out.println("----------- System Properties -----------");
System.getProperties().forEach((k, v) -> print((String) k, v));
System.out.println();
System.out.println("--------- Environment Variables ---------");
Utils.getenv().forEach(Engine::print);
System.out.println();
System.out.println("-------------- Directories --------------");
try {
Path temp = Paths.get(System.getProperty("java.io.tmpdir"));
System.out.println("temp directory: " + temp);
Path tmpFile = Files.createTempFile("test", ".tmp");
Files.delete(tmpFile);
Path cacheDir = Utils.getCacheDir();
System.out.println("DJL cache directory: " + cacheDir.toAbsolutePath());
Path path = Utils.getEngineCacheDir();
System.out.println("Engine cache directory: " + path.toAbsolutePath());
Files.createDirectories(path);
if (!Files.isWritable(path)) {
System.out.println("Engine cache directory is not writable!!!");
}
} catch (Throwable e) {
e.printStackTrace(System.out);
}
System.out.println();
System.out.println("------------------ CUDA -----------------");
int gpuCount = CudaUtils.getGpuCount();
System.out.println("GPU Count: " + gpuCount);
if (gpuCount > 0) {
System.out.println("CUDA: " + CudaUtils.getCudaVersionString());
System.out.println("ARCH: " + CudaUtils.getComputeCapability(0));
}
for (int i = 0; i < gpuCount; ++i) {
Device device = Device.gpu(i);
MemoryUsage mem = CudaUtils.getGpuMemory(device);
System.out.println("GPU(" + i + ") memory used: " + mem.getCommitted() + " bytes");
}
System.out.println();
System.out.println("----------------- Engines ---------------");
System.out.println("DJL version: " + getDjlVersion());
System.out.println("Default Engine: " + Engine.getInstance());
System.out.println("Default Device: " + Engine.getInstance().defaultDevice());
for (EngineProvider provider : ALL_ENGINES.values()) {
System.out.println(provider.getEngineName() + ": " + provider.getEngineRank());
}
}
private static void print(String key, Object value) {
if (PATTERN.matcher(key).find()) {
value = "*********";
}
System.out.println(key + ": " + value); // NOPMD
}
}
|
0
|
java-sources/ai/djl/api/0.34.0/ai/djl
|
java-sources/ai/djl/api/0.34.0/ai/djl/engine/EngineException.java
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl.engine;
/** Thrown to indicate that a native error is raised from the underlying {@link Engine}. */
public class EngineException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new exception with the specified detail message. The cause is not initialized,
* and may subsequently be initialized by a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for later retrieval by the
* {@link #getMessage()} method.
*/
public EngineException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* <p>Note that the detail message associated with {@code cause} is <i>not</i> automatically
* incorporated in this exception's detail message.
*
* @param message the detail message (which is saved for later retrieval by the {@link
* #getMessage()} method)
* @param cause the cause (which is saved for later retrieval by the {@link #getCause()}
* method). (A {@code null} value is permitted, and indicates that the cause is nonexistent
* or unknown.)
*/
public EngineException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause and a detail message of {@code
* (cause==null ? null : cause.toString())} (which typically contains the class and detail
* message of {@code cause}). This constructor is useful for exceptions that are little more
* than wrappers for other throwables (for example, {@link
* java.security.PrivilegedActionException}).
*
* @param cause the cause (which is saved for later retrieval by the {@link #getCause()}
* method). (A {@code null} value is permitted, and indicates that the cause is nonexistent
* or unknown.)
*/
public EngineException(Throwable cause) {
super(cause);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.