repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/dto/FeAnalysisDemographicCriteriaDTO.java
src/main/java/org/ohdsi/webapi/feanalysis/dto/FeAnalysisDemographicCriteriaDTO.java
package org.ohdsi.webapi.feanalysis.dto; import com.fasterxml.jackson.annotation.JsonProperty; import org.ohdsi.circe.cohortdefinition.DemographicCriteria; public class FeAnalysisDemographicCriteriaDTO extends BaseFeAnalysisCriteriaDTO { @JsonProperty("expression") private DemographicCriteria expression; public FeAnalysisDemographicCriteriaDTO() { } public FeAnalysisDemographicCriteriaDTO(Long id, String name, DemographicCriteria expression) { super(id, name); this.expression = expression; } public DemographicCriteria getExpression() { return expression; } public void setExpression(DemographicCriteria expression) { this.expression = expression; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/dto/FeAnalysisDTO.java
src/main/java/org/ohdsi/webapi/feanalysis/dto/FeAnalysisDTO.java
package org.ohdsi.webapi.feanalysis.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.ohdsi.analysis.cohortcharacterization.design.FeatureAnalysis; import org.ohdsi.webapi.feanalysis.FeAnalysisDeserializer; @JsonDeserialize(using = FeAnalysisDeserializer.class) public class FeAnalysisDTO extends FeAnalysisShortDTO implements FeatureAnalysis{ private String value; @JsonProperty("design") private Object design; public String getValue() { return value; } public void setValue(final String value) { this.value = value; } @Override public Object getDesign() { return design; } public void setDesign(final Object design) { this.design = design; } @Override public String getDescr() { return getDescription(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisWithDistributionCriteriaEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisWithDistributionCriteriaEntity.java
package org.ohdsi.webapi.feanalysis.domain; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("CRITERIA_SET_DISTRIBUTION") public class FeAnalysisWithDistributionCriteriaEntity extends FeAnalysisWithCriteriaEntity<FeAnalysisDistributionCriteriaEntity> { public FeAnalysisWithDistributionCriteriaEntity() { } public FeAnalysisWithDistributionCriteriaEntity(FeAnalysisWithCriteriaEntity analysis) { super(analysis); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisWindowedCriteriaEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisWindowedCriteriaEntity.java
package org.ohdsi.webapi.feanalysis.domain; import org.ohdsi.analysis.Utils; import org.ohdsi.analysis.cohortcharacterization.design.WindowedCriteriaFeature; import org.ohdsi.circe.cohortdefinition.WindowedCriteria; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("WINDOWED_CRITERIA") public class FeAnalysisWindowedCriteriaEntity extends FeAnalysisDistributionCriteriaEntity<WindowedCriteria> implements WindowedCriteriaFeature { @Override public WindowedCriteria getExpression() { return Utils.deserialize(this.getExpressionString(), WindowedCriteria.class); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisWithCriteriaEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisWithCriteriaEntity.java
package org.ohdsi.webapi.feanalysis.domain; import org.ohdsi.analysis.cohortcharacterization.design.FeatureAnalysisWithCriteria; import org.ohdsi.circe.cohortdefinition.ConceptSet; import javax.persistence.*; import java.util.Collections; import java.util.List; import java.util.Objects; @Entity public abstract class FeAnalysisWithCriteriaEntity<T extends FeAnalysisCriteriaEntity> extends FeAnalysisEntity<List<T>> implements FeatureAnalysisWithCriteria<T, Integer> { @OneToMany(targetEntity = FeAnalysisCriteriaEntity.class, fetch = FetchType.EAGER, mappedBy = "featureAnalysis", cascade = {CascadeType.MERGE, CascadeType.REMOVE, CascadeType.REFRESH, CascadeType.DETACH}) private List<T> design; @OneToOne(fetch = FetchType.EAGER, mappedBy = "featureAnalysis", cascade = CascadeType.ALL) private FeAnalysisConcepsetEntity conceptSetEntity; public FeAnalysisWithCriteriaEntity() { super(); } public FeAnalysisWithCriteriaEntity(final FeAnalysisWithCriteriaEntity analysis) { super(analysis); } @Override public List<T> getDesign() { return design; } @Override public void setDesign(List<T> design) { this.design = design; } public FeAnalysisConcepsetEntity getConceptSetEntity() { return conceptSetEntity; } public void setConceptSetEntity(FeAnalysisConcepsetEntity conceptSetEntity) { this.conceptSetEntity = conceptSetEntity; } public List<ConceptSet> getConceptSets() { return Objects.nonNull(this.conceptSetEntity) ? this.conceptSetEntity.getConceptSets() : Collections.emptyList(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisDistributionCriteriaEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisDistributionCriteriaEntity.java
package org.ohdsi.webapi.feanalysis.domain; import javax.persistence.Entity; @Entity public abstract class FeAnalysisDistributionCriteriaEntity<T> extends FeAnalysisCriteriaEntity { public abstract T getExpression(); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisCriteriaEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisCriteriaEntity.java
package org.ohdsi.webapi.feanalysis.domain; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.DiscriminatorOptions; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; import org.ohdsi.analysis.WithId; @Entity @Table(name = "fe_analysis_criteria") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "criteria_type") @DiscriminatorOptions(force = false) public abstract class FeAnalysisCriteriaEntity implements WithId<Long> { @Id @GenericGenerator( name = "fe_analysis_criteria_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "fe_analysis_criteria_sequence"), @Parameter(name = "increment_size", value = "1") } ) @GeneratedValue(generator = "fe_analysis_criteria_generator") private Long id; @Column private String name; @Lob @Column(name = "expression") @Type(type = "org.hibernate.type.TextType") private String expressionString; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "fe_aggregate_id") private FeAnalysisAggregateEntity aggregate; @ManyToOne(optional = false, targetEntity = FeAnalysisWithCriteriaEntity.class, fetch = FetchType.LAZY) @JoinColumn(name = "fe_analysis_id") private FeAnalysisWithCriteriaEntity featureAnalysis; public String getName() { return name; } public void setName(final String name) { this.name = name; } @Override public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public FeAnalysisWithCriteriaEntity getFeatureAnalysis() { return featureAnalysis; } public void setFeatureAnalysis(final FeAnalysisWithCriteriaEntity featureAnalysis) { this.featureAnalysis = featureAnalysis; } public String getExpressionString() { return expressionString; } public void setExpressionString(final String expressionString) { this.expressionString = expressionString; } public FeAnalysisAggregateEntity getAggregate() { return aggregate; } public void setAggregate(FeAnalysisAggregateEntity aggregate) { this.aggregate = aggregate; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisDemographicCriteriaEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisDemographicCriteriaEntity.java
package org.ohdsi.webapi.feanalysis.domain; import org.ohdsi.analysis.Utils; import org.ohdsi.analysis.cohortcharacterization.design.DemographicCriteriaFeature; import org.ohdsi.circe.cohortdefinition.DemographicCriteria; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("DEMOGRAPHIC_CRITERIA") public class FeAnalysisDemographicCriteriaEntity extends FeAnalysisDistributionCriteriaEntity<DemographicCriteria> implements DemographicCriteriaFeature { @Override public DemographicCriteria getExpression() { return Utils.deserialize(this.getExpressionString(), DemographicCriteria.class); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisEntity.java
package org.ohdsi.webapi.feanalysis.domain; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.Table; import org.apache.commons.lang3.ObjectUtils; import org.hibernate.annotations.DiscriminatorFormula; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; import org.ohdsi.analysis.cohortcharacterization.design.CcResultType; import org.ohdsi.analysis.cohortcharacterization.design.FeatureAnalysis; import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisDomain; import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisType; import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity; import org.ohdsi.webapi.model.CommonEntity; @Entity @Table(name = "fe_analysis") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorFormula( "CASE WHEN type = 'CRITERIA_SET' THEN CONCAT(CONCAT(type,'_'),stat_type) " + "ELSE type END" ) public abstract class FeAnalysisEntity<T> extends CommonEntity<Integer> implements FeatureAnalysis<T, Integer>, Comparable<FeAnalysisEntity<String>> { public FeAnalysisEntity() { } public FeAnalysisEntity(final FeAnalysisEntity<T> entityForCopy) { this.id = entityForCopy.id; this.type = entityForCopy.type; this.name = entityForCopy.name; this.setDesign(entityForCopy.getDesign()); this.domain = entityForCopy.domain; this.descr = entityForCopy.descr; this.isLocked = entityForCopy.isLocked; this.statType = entityForCopy.statType; } @Id @GenericGenerator( name = "fe_analysis_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "fe_analysis_sequence"), @Parameter(name = "increment_size", value = "1") } ) @GeneratedValue(generator = "fe_analysis_generator") private Integer id; @Column @Enumerated(EnumType.STRING) private StandardFeatureAnalysisType type; @Column private String name; @Lob @Type(type = "org.hibernate.type.TextType") @Column(name = "design", insertable = false, updatable = false) private String rawDesign; @Column @Enumerated(EnumType.STRING) private StandardFeatureAnalysisDomain domain; @Column private String descr; @Column(name = "is_locked") private Boolean isLocked; @ManyToMany(targetEntity = CohortCharacterizationEntity.class, fetch = FetchType.LAZY, mappedBy = "featureAnalyses") private Set<CohortCharacterizationEntity> cohortCharacterizations = new HashSet<>(); @Column(name = "stat_type") @Enumerated(value = EnumType.STRING) private CcResultType statType; @Column(name = "supports_annual", updatable = false, insertable = false) private Boolean supportsAnnual; @Column(name = "supports_temporal", updatable = false, insertable = false) private Boolean supportsTemporal; @Override public Integer getId() { return id; } @Override public StandardFeatureAnalysisType getType() { return type; } @Override public String getName() { return name; } @Override public StandardFeatureAnalysisDomain getDomain() { return domain; } @Override public String getDescr() { return descr; } @Override public abstract T getDesign(); public abstract void setDesign(T design); public boolean isPreset() { return this.type == StandardFeatureAnalysisType.PRESET; } public boolean isCustom() { return this.type == StandardFeatureAnalysisType.CUSTOM_FE; } public boolean isCriteria() { return this.type == StandardFeatureAnalysisType.CRITERIA_SET; } public void setId(final Integer id) { this.id = id; } public void setType(final StandardFeatureAnalysisType type) { this.type = type; } public void setName(final String name) { this.name = name; } public void setDomain(final StandardFeatureAnalysisDomain domain) { this.domain = domain; } public void setDescr(final String descr) { this.descr = descr; } public String getRawDesign() { return rawDesign; } @Override public boolean equals(final Object o) { if (this == o) return true; if (!(o instanceof FeAnalysisEntity)) return false; final FeAnalysisEntity that = (FeAnalysisEntity) o; if (getId() != null && that.getId() != null) { return Objects.equals(getId(), that.getId()); } else { return Objects.equals(getType(), that.getType()) && Objects.equals(getDesign(), that.getDesign()); } } @Override public int hashCode() { return Objects.hash(getId()); } public Boolean getLocked() { return isLocked; } public void setLocked(final Boolean locked) { isLocked = locked; } public Set<CohortCharacterizationEntity> getCohortCharacterizations() { return cohortCharacterizations; } public void setCohortCharacterizations(final Set<CohortCharacterizationEntity> cohortCharacterizations) { this.cohortCharacterizations = cohortCharacterizations; } @Override public int compareTo(final FeAnalysisEntity o) { return ObjectUtils.compare(this.name, o.name); } public CcResultType getStatType() { return statType; } public void setStatType(final CcResultType statType) { this.statType = statType; } public Boolean getSupportsAnnual() { return supportsAnnual; } public void setSupportsAnnual(Boolean supportsAnnual) { this.supportsAnnual = supportsAnnual; } public Boolean getSupportsTemporal() { return supportsTemporal; } public void setSupportsTemporal(Boolean supportsTemporal) { this.supportsTemporal = supportsTemporal; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisWithPrevalenceCriteriaEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisWithPrevalenceCriteriaEntity.java
package org.ohdsi.webapi.feanalysis.domain; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("CRITERIA_SET_PREVALENCE") public class FeAnalysisWithPrevalenceCriteriaEntity extends FeAnalysisWithCriteriaEntity<FeAnalysisCriteriaGroupEntity> { public FeAnalysisWithPrevalenceCriteriaEntity() { } public FeAnalysisWithPrevalenceCriteriaEntity(FeAnalysisWithCriteriaEntity analysis) { super(analysis); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisConcepsetEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisConcepsetEntity.java
package org.ohdsi.webapi.feanalysis.domain; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.ohdsi.webapi.common.CommonConceptSetEntity; @Entity @Table(name = "fe_analysis_conceptset") public class FeAnalysisConcepsetEntity extends CommonConceptSetEntity { @Id @GenericGenerator( name = "fe_conceptset_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "fe_conceptset_sequence"), @Parameter(name = "increment_size", value = "1") } ) @GeneratedValue(generator = "fe_conceptset_generator") private Long id; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "fe_analysis_id") private FeAnalysisWithCriteriaEntity featureAnalysis; public FeAnalysisConcepsetEntity() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public FeAnalysisWithCriteriaEntity getFeatureAnalysis() { return featureAnalysis; } public void setFeatureAnalysis(FeAnalysisWithCriteriaEntity featureAnalysis) { this.featureAnalysis = featureAnalysis; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisWithStringEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisWithStringEntity.java
package org.ohdsi.webapi.feanalysis.domain; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Lob; import org.hibernate.annotations.Type; import org.ohdsi.analysis.cohortcharacterization.design.FeatureAnalysis; @Entity @DiscriminatorValue("not null") public class FeAnalysisWithStringEntity extends FeAnalysisEntity<String> { public FeAnalysisWithStringEntity() { super(); } public FeAnalysisWithStringEntity(final FeAnalysisWithStringEntity analysis) { super(analysis); } @Lob @Type(type = "org.hibernate.type.TextType") private String design; @Override public String getDesign() { return design; } public void setDesign(final String design) { this.design = design; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisAggregateEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisAggregateEntity.java
package org.ohdsi.webapi.feanalysis.domain; import org.apache.commons.lang3.StringUtils; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import org.ohdsi.analysis.TableJoin; import org.ohdsi.analysis.WithId; import org.ohdsi.analysis.cohortcharacterization.design.AggregateFunction; import org.ohdsi.analysis.cohortcharacterization.design.FeatureAnalysisAggregate; import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisDomain; import org.ohdsi.circe.cohortdefinition.builders.CriteriaColumn; import org.ohdsi.webapi.common.orm.EnumListType; import javax.persistence.*; import java.util.List; @Entity @Table(name = "fe_analysis_aggregate") @TypeDef(typeClass = EnumListType.class, name = "enum-list") public class FeAnalysisAggregateEntity implements FeatureAnalysisAggregate, WithId<Integer> { @Id @GenericGenerator( name = "fe_aggregate_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "fe_aggregate_sequence"), @Parameter(name = "increment_size", value = "1") } ) @GeneratedValue(generator = "fe_aggregate_generator") private Integer id; @Column private String name; @Column @Enumerated(value = EnumType.STRING) private StandardFeatureAnalysisDomain domain; @Column(name = "agg_function") @Enumerated(value = EnumType.STRING) private AggregateFunction function; @Column private String expression; @Column(name = "join_table") private String joinTable; @Column(name = "join_type") @Enumerated(EnumType.STRING) private TableJoin joinType; @Column(name = "join_condition") private String joinCondition; @Column(name = "is_default") private boolean isDefault; @Column(name = "missing_means_zero") private boolean isMissingMeansZero; @Column(name = "criteria_columns") @Type(type = "enum-list", parameters = { @Parameter(name = "enumClass", value = "org.ohdsi.circe.cohortdefinition.builders.CriteriaColumn") }) private List<CriteriaColumn> columns; @Override public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public StandardFeatureAnalysisDomain getDomain() { return domain; } public void setDomain(StandardFeatureAnalysisDomain domain) { this.domain = domain; } public AggregateFunction getFunction() { return function; } @Override public List<CriteriaColumn> getAdditionalColumns() { return columns; } public void setCriteriaColumns(List<CriteriaColumn> columns) { this.columns = columns; } public void setFunction(AggregateFunction function) { this.function = function; } public String getExpression() { return expression; } @Override public boolean hasQuery() { return StringUtils.isNotBlank(this.joinTable); } public void setExpression(String expression) { this.expression = expression; } public String getJoinTable() { return joinTable; } public void setJoinTable(String joinTable) { this.joinTable = joinTable; } public TableJoin getJoinType() { return joinType; } public void setJoinType(TableJoin joinType) { this.joinType = joinType; } public String getJoinCondition() { return joinCondition; } public void setJoinCondition(String joinCondition) { this.joinCondition = joinCondition; } public boolean isDefault() { return isDefault; } public void setDefault(boolean aDefault) { isDefault = aDefault; } public boolean isMissingMeansZero() { return isMissingMeansZero; } public void setMissingMeansZero(boolean aDefault) { isMissingMeansZero = aDefault; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisCriteriaGroupEntity.java
src/main/java/org/ohdsi/webapi/feanalysis/domain/FeAnalysisCriteriaGroupEntity.java
package org.ohdsi.webapi.feanalysis.domain; import org.ohdsi.analysis.Utils; import org.ohdsi.analysis.cohortcharacterization.design.CriteriaFeature; import org.ohdsi.circe.cohortdefinition.CriteriaGroup; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("CRITERIA_GROUP") public class FeAnalysisCriteriaGroupEntity extends FeAnalysisCriteriaEntity implements CriteriaFeature { @Override public CriteriaGroup getExpression() { return getCriteriaGroup(); } private CriteriaGroup getCriteriaGroup() { return Utils.deserialize(this.getExpressionString(), CriteriaGroup.class); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/repository/FeAnalysisWithStringEntityRepository.java
src/main/java/org/ohdsi/webapi/feanalysis/repository/FeAnalysisWithStringEntityRepository.java
package org.ohdsi.webapi.feanalysis.repository; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisWithStringEntity; import java.util.Collection; import java.util.List; public interface FeAnalysisWithStringEntityRepository extends BaseFeAnalysisEntityRepository<FeAnalysisWithStringEntity> { List<FeAnalysisWithStringEntity> findByDesignIn(Collection<String> names); List<FeAnalysisWithStringEntity> findByDesign(String design); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/repository/FeAnalysisAggregateRepository.java
src/main/java/org/ohdsi/webapi/feanalysis/repository/FeAnalysisAggregateRepository.java
package org.ohdsi.webapi.feanalysis.repository; import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisDomain; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisAggregateEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; import java.util.Optional; public interface FeAnalysisAggregateRepository extends JpaRepository<FeAnalysisAggregateEntity, Integer> { List<FeAnalysisAggregateEntity> findByDomain(StandardFeatureAnalysisDomain domain); @Query("select fa from FeAnalysisAggregateEntity fa where fa.isDefault = true") Optional<FeAnalysisAggregateEntity> findDefault(); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/repository/FeAnalysisEntityRepository.java
src/main/java/org/ohdsi/webapi/feanalysis/repository/FeAnalysisEntityRepository.java
package org.ohdsi.webapi.feanalysis.repository; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisEntity; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; import java.util.Set; public interface FeAnalysisEntityRepository extends BaseFeAnalysisEntityRepository<FeAnalysisEntity> { @Query("Select fe FROM FeAnalysisEntity fe WHERE fe.name LIKE ?1 ESCAPE '\\'") List<FeAnalysisEntity> findAllByNameStartsWith(String pattern); @Query("SELECT COUNT(fe) FROM FeAnalysisEntity fe WHERE fe.name = :name and fe.id <> :id") int getCountFeWithSameName(@Param("id") Integer id, @Param("name") String name); @Query("SELECT fe FROM FeAnalysisEntity fe WHERE fe.id IN :ids") Set<FeAnalysisEntity> findByListIds(@Param("ids") List<Integer> ids); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/repository/FeAnalysisWithCriteriaEntityRepository.java
src/main/java/org/ohdsi/webapi/feanalysis/repository/FeAnalysisWithCriteriaEntityRepository.java
package org.ohdsi.webapi.feanalysis.repository; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisWithCriteriaEntity; public interface FeAnalysisWithCriteriaEntityRepository extends BaseFeAnalysisEntityRepository<FeAnalysisWithCriteriaEntity> { }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/repository/BaseFeAnalysisEntityRepository.java
src/main/java/org/ohdsi/webapi/feanalysis/repository/BaseFeAnalysisEntityRepository.java
package org.ohdsi.webapi.feanalysis.repository; import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraph; import com.cosium.spring.data.jpa.entity.graph.repository.EntityGraphJpaRepository; import java.util.List; import java.util.Optional; import java.util.Set; import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisType; import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisEntity; import org.ohdsi.webapi.prediction.PredictionAnalysis; import org.springframework.data.repository.NoRepositoryBean; @NoRepositoryBean public interface BaseFeAnalysisEntityRepository<T extends FeAnalysisEntity> extends EntityGraphJpaRepository<T, Integer> { Set<T> findAllByCohortCharacterizations(CohortCharacterizationEntity cohortCharacterization); List<T> findAllByType(StandardFeatureAnalysisType preset); Optional<T> findById(Integer id); Optional<T> findById(Integer id, EntityGraph entityGraph); Optional<T> findByName(String name); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/repository/FeAnalysisCriteriaRepository.java
src/main/java/org/ohdsi/webapi/feanalysis/repository/FeAnalysisCriteriaRepository.java
package org.ohdsi.webapi.feanalysis.repository; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisCriteriaEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface FeAnalysisCriteriaRepository extends JpaRepository<FeAnalysisCriteriaEntity, Long> { List<FeAnalysisCriteriaEntity> findAllByFeatureAnalysisId(Integer id); @Query("select fa from FeAnalysisCriteriaEntity AS fa JOIN FETCH fa.featureAnalysis where expression = ?1") List<FeAnalysisCriteriaEntity> findAllByExpressionString(String expression); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/converter/BaseFeAnalysisDTOToFeAnalysisConverter.java
src/main/java/org/ohdsi/webapi/feanalysis/converter/BaseFeAnalysisDTOToFeAnalysisConverter.java
package org.ohdsi.webapi.feanalysis.converter; import org.apache.commons.lang3.StringUtils; import org.ohdsi.webapi.converter.BaseConversionServiceAwareConverter; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisEntity; import org.ohdsi.webapi.feanalysis.dto.FeAnalysisShortDTO; public abstract class BaseFeAnalysisDTOToFeAnalysisConverter<D extends FeAnalysisShortDTO, T extends FeAnalysisEntity> extends BaseConversionServiceAwareConverter<D, T> { @Override public T convert(D source) { final T result = createResultObject(source); result.setId(source.getId()); result.setDescr(source.getDescription()); result.setDomain(source.getDomain()); result.setName(StringUtils.trim(source.getName())); result.setType(source.getType()); result.setStatType(source.getStatType()); result.setSupportsAnnual(source.getSupportsAnnual()); result.setSupportsTemporal(source.getSupportsTemporal()); return result; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/converter/FeatureAnalysisAggregateToDTOConverter.java
src/main/java/org/ohdsi/webapi/feanalysis/converter/FeatureAnalysisAggregateToDTOConverter.java
package org.ohdsi.webapi.feanalysis.converter; import com.odysseusinc.arachne.commons.converter.BaseConvertionServiceAwareConverter; import org.ohdsi.analysis.cohortcharacterization.design.FeatureAnalysisAggregate; import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisDomain; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisAggregateEntity; import org.ohdsi.webapi.feanalysis.dto.FeAnalysisAggregateDTO; import org.springframework.stereotype.Component; @Component public class FeatureAnalysisAggregateToDTOConverter extends BaseConvertionServiceAwareConverter<FeatureAnalysisAggregate, FeAnalysisAggregateDTO> { @Override protected FeAnalysisAggregateDTO createResultObject(FeatureAnalysisAggregate featureAnalysisAggregate) { return new FeAnalysisAggregateDTO(); } @Override protected void convert(FeatureAnalysisAggregate source, FeAnalysisAggregateDTO dto) { if (source instanceof FeAnalysisAggregateEntity) { dto.setId(source.getId()); } dto.setDomain((StandardFeatureAnalysisDomain) source.getDomain()); dto.setName(source.getName()); dto.setExpression(source.getExpression()); dto.setFunction(source.getFunction()); dto.setJoinTable(source.getJoinTable()); dto.setJoinType(source.getJoinType()); dto.setJoinCondition(source.getJoinCondition()); dto.setAdditionalColumns(source.getAdditionalColumns()); if (source instanceof FeAnalysisAggregateEntity) { dto.setDefault(((FeAnalysisAggregateEntity) source).isDefault()); } dto.setMissingMeansZero(source.isMissingMeansZero()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisDTOToFeAnalysisConverter.java
src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisDTOToFeAnalysisConverter.java
package org.ohdsi.webapi.feanalysis.converter; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisEntity; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisWithCriteriaEntity; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisWithStringEntity; import org.ohdsi.webapi.feanalysis.dto.FeAnalysisDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Component; import java.util.Objects; import static org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisType.CRITERIA_SET; @Component public class FeAnalysisDTOToFeAnalysisConverter extends BaseFeAnalysisDTOToFeAnalysisConverter<FeAnalysisDTO, FeAnalysisEntity> { @Autowired private ConversionService conversionService; @Override public FeAnalysisEntity convert(final FeAnalysisDTO source) { return super.convert(source); } @Override protected FeAnalysisEntity createResultObject(final FeAnalysisDTO source) { if (Objects.equals(source.getType(), CRITERIA_SET)) { return conversionService.convert(source, FeAnalysisWithCriteriaEntity.class); } else { return conversionService.convert(source, FeAnalysisWithStringEntity.class); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/converter/CcFeAnalysisEntityToFeAnalysisShortDTOConverter.java
src/main/java/org/ohdsi/webapi/feanalysis/converter/CcFeAnalysisEntityToFeAnalysisShortDTOConverter.java
package org.ohdsi.webapi.feanalysis.converter; import org.ohdsi.webapi.cohortcharacterization.domain.CcFeAnalysisEntity; import org.ohdsi.webapi.converter.BaseConversionServiceAwareConverter; import org.ohdsi.webapi.feanalysis.dto.FeAnalysisShortDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.stereotype.Component; @Component public class CcFeAnalysisEntityToFeAnalysisShortDTOConverter extends BaseConversionServiceAwareConverter<CcFeAnalysisEntity, FeAnalysisShortDTO> { @Autowired private GenericConversionService conversionService; @Override public FeAnalysisShortDTO convert(CcFeAnalysisEntity source) { FeAnalysisShortDTO dto = conversionService.convert(source.getFeatureAnalysis(), FeAnalysisShortDTO.class); dto.setIncludeAnnual(source.getIncludeAnnual()); dto.setIncludeTemporal(source.getIncludeTemporal()); return dto; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisEntityToFeAnalysisDTOConverter.java
src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisEntityToFeAnalysisDTOConverter.java
package org.ohdsi.webapi.feanalysis.converter; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.collections4.CollectionUtils; import org.ohdsi.webapi.feanalysis.domain.*; import org.ohdsi.webapi.feanalysis.dto.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.hibernate.Hibernate; import java.util.Collections; import java.util.Optional; import java.util.stream.Collectors; import static org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisType.CRITERIA_SET; @Component public class FeAnalysisEntityToFeAnalysisDTOConverter extends BaseFeAnalysisEntityToFeAnalysisDTOConverter<FeAnalysisDTO> { @Autowired private ObjectMapper objectMapper; @Override public FeAnalysisDTO convert(final FeAnalysisEntity source) { final FeAnalysisDTO dto = super.convert(source); dto.setDesign(convertDesignToJson(source)); dto.setSupportsAnnual(source.getSupportsAnnual()); dto.setSupportsTemporal(source.getSupportsTemporal()); if (CRITERIA_SET.equals(source.getType())){ FeAnalysisWithConceptSetDTO dtoWithConceptSet = (FeAnalysisWithConceptSetDTO) dto; FeAnalysisWithCriteriaEntity<?> sourceWithCriteria = (FeAnalysisWithCriteriaEntity) source; dtoWithConceptSet.setConceptSets(sourceWithCriteria.getConceptSets()); } return dto; } @Override protected FeAnalysisDTO createResultObject(FeAnalysisEntity feAnalysisEntity) { return Optional.ofNullable(feAnalysisEntity.getType()).map(type -> { switch (type) { case CRITERIA_SET: return new FeAnalysisWithConceptSetDTO(); default: return new FeAnalysisDTO(); } }).orElseGet(() -> new FeAnalysisDTO()); } private Object convertDesignToJson(final FeAnalysisEntity source) { return Optional.ofNullable(source.getType()).map(type -> { switch (type) { case CRITERIA_SET: FeAnalysisWithCriteriaEntity<?> sourceWithCriteria = (FeAnalysisWithCriteriaEntity<?>) source; Hibernate.initialize(sourceWithCriteria.getDesign()); // Explicitly initialize the collection if (CollectionUtils.isEmpty(sourceWithCriteria.getDesign())) { return Collections.emptyList(); } return sourceWithCriteria.getDesign() .stream() .map(this::convertCriteria) .map(c -> (JsonNode) objectMapper.valueToTree(c)) .collect(Collectors.toList()); default: return source.getDesign(); } }).orElseGet(() -> source.getDesign()); } private BaseFeAnalysisCriteriaDTO convertCriteria(FeAnalysisCriteriaEntity criteriaEntity){ BaseFeAnalysisCriteriaDTO criteriaDTO; if (criteriaEntity instanceof FeAnalysisCriteriaGroupEntity) { FeAnalysisCriteriaGroupEntity groupEntity = (FeAnalysisCriteriaGroupEntity) criteriaEntity; criteriaDTO = new FeAnalysisCriteriaDTO(groupEntity.getId(), groupEntity.getName(), groupEntity.getExpression()); } else if (criteriaEntity instanceof FeAnalysisWindowedCriteriaEntity) { FeAnalysisWindowedCriteriaEntity w = (FeAnalysisWindowedCriteriaEntity) criteriaEntity; criteriaDTO = new FeAnalysisWindowedCriteriaDTO(w.getId(), w.getName(), w.getExpression()); } else if (criteriaEntity instanceof FeAnalysisDemographicCriteriaEntity) { FeAnalysisDemographicCriteriaEntity d = (FeAnalysisDemographicCriteriaEntity) criteriaEntity; criteriaDTO = new FeAnalysisDemographicCriteriaDTO(d.getId(), d.getName(), d.getExpression()); } else { throw new IllegalArgumentException(String.format("Cannot convert criteria entity, %s is not supported", criteriaEntity)); } criteriaDTO.setAggregate(conversionService.convert(criteriaEntity.getAggregate(), FeAnalysisAggregateDTO.class)); return criteriaDTO; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisAggregateDTOToEntityConverter.java
src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisAggregateDTOToEntityConverter.java
package org.ohdsi.webapi.feanalysis.converter; import com.odysseusinc.arachne.commons.converter.BaseConvertionServiceAwareConverter; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisAggregateEntity; import org.ohdsi.webapi.feanalysis.dto.FeAnalysisAggregateDTO; import org.ohdsi.webapi.feanalysis.repository.FeAnalysisAggregateRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Objects; @Component public class FeAnalysisAggregateDTOToEntityConverter extends BaseConvertionServiceAwareConverter<FeAnalysisAggregateDTO, FeAnalysisAggregateEntity> { @Autowired private FeAnalysisAggregateRepository aggregateRepository; @Override protected FeAnalysisAggregateEntity createResultObject(FeAnalysisAggregateDTO feAnalysisAggregateDTO) { return new FeAnalysisAggregateEntity(); } @Override public FeAnalysisAggregateEntity convert(FeAnalysisAggregateDTO dto) { if (Objects.nonNull(dto.getId())) { return aggregateRepository.getOne(dto.getId()); } else { return aggregateRepository.findDefault().orElse(null); } } @Override protected void convert(FeAnalysisAggregateDTO dto, FeAnalysisAggregateEntity entity) { } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisDTOToFeAnalysisWithStringConverter.java
src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisDTOToFeAnalysisWithStringConverter.java
package org.ohdsi.webapi.feanalysis.converter; import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisType; import org.ohdsi.webapi.feanalysis.dto.FeAnalysisDTO; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisWithStringEntity; import org.springframework.stereotype.Component; @Component public class FeAnalysisDTOToFeAnalysisWithStringConverter extends BaseFeAnalysisDTOToFeAnalysisConverter<FeAnalysisDTO, FeAnalysisWithStringEntity> { @Override public FeAnalysisWithStringEntity convert(final FeAnalysisDTO source) { if (source.getType() != StandardFeatureAnalysisType.CUSTOM_FE && source.getType() != StandardFeatureAnalysisType.PRESET) { throw new IllegalArgumentException("Only PRESET and CUSTOME_FE analyses can have design of String type"); } final FeAnalysisWithStringEntity baseEntity = super.convert(source); baseEntity.setDesign(String.valueOf(source.getDesign())); return baseEntity; } @Override protected FeAnalysisWithStringEntity createResultObject() { return new FeAnalysisWithStringEntity(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisShortDTOToFeaAnalysisConverter.java
src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisShortDTOToFeaAnalysisConverter.java
package org.ohdsi.webapi.feanalysis.converter; import org.ohdsi.analysis.cohortcharacterization.design.CcResultType; import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisType; import org.ohdsi.webapi.feanalysis.domain.*; import org.ohdsi.webapi.feanalysis.dto.FeAnalysisShortDTO; import org.springframework.stereotype.Component; import java.util.Objects; @Component public class FeAnalysisShortDTOToFeaAnalysisConverter extends BaseFeAnalysisDTOToFeAnalysisConverter<FeAnalysisShortDTO, FeAnalysisEntity> { @Override protected FeAnalysisEntity createResultObject(FeAnalysisShortDTO dto) { return Objects.equals(dto.getType(), StandardFeatureAnalysisType.CRITERIA_SET) ? Objects.equals(dto.getStatType(), CcResultType.PREVALENCE) ? new FeAnalysisWithPrevalenceCriteriaEntity() : new FeAnalysisWithDistributionCriteriaEntity() : new FeAnalysisWithStringEntity(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/converter/BaseFeAnalysisEntityToFeAnalysisDTOConverter.java
src/main/java/org/ohdsi/webapi/feanalysis/converter/BaseFeAnalysisEntityToFeAnalysisDTOConverter.java
package org.ohdsi.webapi.feanalysis.converter; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisEntity; import org.ohdsi.webapi.feanalysis.dto.FeAnalysisShortDTO; import org.ohdsi.webapi.service.converters.BaseCommonEntityToDTOConverter; public abstract class BaseFeAnalysisEntityToFeAnalysisDTOConverter<T extends FeAnalysisShortDTO> extends BaseCommonEntityToDTOConverter<FeAnalysisEntity<?>, T> { @Override public void doConvert(FeAnalysisEntity<?> source, T target) { target.setType(source.getType()); target.setName(source.getName()); target.setId(source.getId()); target.setDomain(source.getDomain()); target.setDescription(source.getDescr()); target.setStatType(source.getStatType()); target.setSupportsAnnual(source.getSupportsAnnual()); target.setSupportsTemporal(source.getSupportsTemporal()); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisDTOToFeAnalysisWithCriteriasConverter.java
src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisDTOToFeAnalysisWithCriteriasConverter.java
package org.ohdsi.webapi.feanalysis.converter; import org.ohdsi.analysis.Utils; import org.ohdsi.analysis.cohortcharacterization.design.CcResultType; import org.ohdsi.analysis.cohortcharacterization.design.StandardFeatureAnalysisType; import org.ohdsi.webapi.feanalysis.domain.*; import org.ohdsi.webapi.feanalysis.dto.*; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.Objects; @Component public class FeAnalysisDTOToFeAnalysisWithCriteriasConverter extends BaseFeAnalysisDTOToFeAnalysisConverter<FeAnalysisDTO, FeAnalysisWithCriteriaEntity> { private static final String RESULT_TYPE_IS_NOT_SUPPORTED = "Result type of %s is not supported"; private static final String DTO_IS_NOT_SUPPORTED = "DTO class is not supported"; @Override public FeAnalysisWithCriteriaEntity convert(final FeAnalysisDTO source) { final FeAnalysisWithCriteriaEntity<? extends FeAnalysisCriteriaEntity> baseEntity = super.convert(source); baseEntity.setStatType(source.getStatType()); List list = getBuilder(source.getStatType()).buildList(source.getDesign()); baseEntity.setDesign(list); baseEntity.getDesign().forEach(c -> c.setFeatureAnalysis(baseEntity)); if (Objects.equals(StandardFeatureAnalysisType.CRITERIA_SET, source.getType())){ convert(baseEntity, (FeAnalysisWithConceptSetDTO) source); } return baseEntity; } private void convert(FeAnalysisWithCriteriaEntity baseEntity, FeAnalysisWithConceptSetDTO source) { FeAnalysisConcepsetEntity concepsetEntity = new FeAnalysisConcepsetEntity(); concepsetEntity.setFeatureAnalysis(baseEntity); concepsetEntity.setRawExpression(Utils.serialize(source.getConceptSets())); baseEntity.setConceptSetEntity(concepsetEntity); } @Override protected FeAnalysisWithCriteriaEntity<? extends FeAnalysisCriteriaEntity> createResultObject(FeAnalysisDTO source) { return getBuilder(source.getStatType()).createFeAnalysisObject(); } interface FeAnalysisBuilder<T extends FeAnalysisCriteriaEntity> { FeAnalysisWithCriteriaEntity<T> createFeAnalysisObject(); List<T> buildList(final Object design); } FeAnalysisBuilder getBuilder(CcResultType statType) { if (Objects.equals(CcResultType.PREVALENCE, statType)) { return new FeAnalysisPrevalenceCriteriaBuilder(conversionService); } else if (Objects.equals(CcResultType.DISTRIBUTION, statType)) { return new FeAnalysisDistributionCriteriaBuilder(conversionService); } throw new IllegalArgumentException(String.format(RESULT_TYPE_IS_NOT_SUPPORTED, statType)); } static abstract class FeAnalysisBuilderSupport<T extends FeAnalysisCriteriaEntity> implements FeAnalysisBuilder<T> { private GenericConversionService conversionService; public FeAnalysisBuilderSupport(GenericConversionService conversionService) { this.conversionService = conversionService; } public List<T> buildList(final Object design) { List<T> result = new ArrayList<>(); if (!(design instanceof List<?>)) { throw new IllegalArgumentException("Design: " + design.toString() + " cannot be converted to Criteria List"); } else { for (final Object criteria : (List<?>) design) { if (!(criteria instanceof BaseFeAnalysisCriteriaDTO)) { throw new IllegalArgumentException("Object " + criteria.toString() + " cannot be converted to Criteria"); } else { final BaseFeAnalysisCriteriaDTO typifiedCriteria = (BaseFeAnalysisCriteriaDTO) criteria; final T criteriaEntity = newCriteriaEntity(typifiedCriteria); criteriaEntity.setExpressionString(Utils.serialize(getExpression(typifiedCriteria))); criteriaEntity.setId(typifiedCriteria.getId()); criteriaEntity.setName(typifiedCriteria.getName()); criteriaEntity.setAggregate(conversionService.convert(typifiedCriteria.getAggregate(), FeAnalysisAggregateEntity.class)); result.add(criteriaEntity); } } } return result; } protected abstract Object getExpression(BaseFeAnalysisCriteriaDTO typifiedCriteria); protected abstract T newCriteriaEntity(BaseFeAnalysisCriteriaDTO typifiedCriteria); } static class FeAnalysisPrevalenceCriteriaBuilder extends FeAnalysisBuilderSupport<FeAnalysisCriteriaGroupEntity>{ public FeAnalysisPrevalenceCriteriaBuilder(GenericConversionService conversionService) { super(conversionService); } @Override public FeAnalysisWithCriteriaEntity<FeAnalysisCriteriaGroupEntity> createFeAnalysisObject() { return new FeAnalysisWithPrevalenceCriteriaEntity(); } @Override protected Object getExpression(BaseFeAnalysisCriteriaDTO typifiedCriteria) { if (typifiedCriteria instanceof FeAnalysisCriteriaDTO) { return ((FeAnalysisCriteriaDTO)typifiedCriteria).getExpression(); } return null; } @Override protected FeAnalysisCriteriaGroupEntity newCriteriaEntity(BaseFeAnalysisCriteriaDTO criteriaDTO) { return new FeAnalysisCriteriaGroupEntity(); } } static class FeAnalysisDistributionCriteriaBuilder extends FeAnalysisBuilderSupport<FeAnalysisDistributionCriteriaEntity> { public FeAnalysisDistributionCriteriaBuilder(GenericConversionService conversionService) { super(conversionService); } @Override public FeAnalysisWithCriteriaEntity<FeAnalysisDistributionCriteriaEntity> createFeAnalysisObject() { return new FeAnalysisWithDistributionCriteriaEntity(); } @Override protected Object getExpression(BaseFeAnalysisCriteriaDTO typifiedCriteria) { if (typifiedCriteria instanceof FeAnalysisWindowedCriteriaDTO) { return ((FeAnalysisWindowedCriteriaDTO)typifiedCriteria).getExpression(); } else if (typifiedCriteria instanceof FeAnalysisDemographicCriteriaDTO) { return ((FeAnalysisDemographicCriteriaDTO)typifiedCriteria).getExpression(); } throw new IllegalArgumentException(DTO_IS_NOT_SUPPORTED); } @Override protected FeAnalysisDistributionCriteriaEntity newCriteriaEntity(BaseFeAnalysisCriteriaDTO criteriaDTO) { if (criteriaDTO instanceof FeAnalysisWindowedCriteriaDTO) { return new FeAnalysisWindowedCriteriaEntity(); } else if (criteriaDTO instanceof FeAnalysisDemographicCriteriaDTO) { return new FeAnalysisDemographicCriteriaEntity(); } throw new IllegalArgumentException(DTO_IS_NOT_SUPPORTED); } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisEntityToFeAnalysisShortDTOConverter.java
src/main/java/org/ohdsi/webapi/feanalysis/converter/FeAnalysisEntityToFeAnalysisShortDTOConverter.java
package org.ohdsi.webapi.feanalysis.converter; import org.ohdsi.webapi.feanalysis.dto.FeAnalysisShortDTO; import org.springframework.stereotype.Component; @Component public class FeAnalysisEntityToFeAnalysisShortDTOConverter extends BaseFeAnalysisEntityToFeAnalysisDTOConverter<FeAnalysisShortDTO> { @Override protected FeAnalysisShortDTO createResultObject() { return new FeAnalysisShortDTO(); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/feanalysis/event/FeAnalysisChangedEvent.java
src/main/java/org/ohdsi/webapi/feanalysis/event/FeAnalysisChangedEvent.java
package org.ohdsi.webapi.feanalysis.event; import org.ohdsi.webapi.feanalysis.domain.FeAnalysisEntity; public class FeAnalysisChangedEvent { private FeAnalysisEntity feAnalysis; public FeAnalysisChangedEvent(FeAnalysisEntity feAnalysis) { this.feAnalysis = feAnalysis; } public FeAnalysisEntity getFeAnalysis() { return feAnalysis; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/info/Info.java
src/main/java/org/ohdsi/webapi/info/Info.java
package org.ohdsi.webapi.info; import java.util.Map; public class Info { private final String version; private final BuildInfo buildInfo; private final Map<String, Map<String, Object>> configuration; public Info(String version, BuildInfo buildInfo, Map<String, Map<String, Object>> configuration) { this.version = version; this.buildInfo = buildInfo; this.configuration = configuration; } public String getVersion() { return version; } public BuildInfo getBuildInfo() { return buildInfo; } public Map<String, Map<String, Object>> getConfiguration() { return configuration; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/info/RepositoryInfo.java
src/main/java/org/ohdsi/webapi/info/RepositoryInfo.java
package org.ohdsi.webapi.info; public class RepositoryInfo { private Integer milestoneId; private String releaseTag; public RepositoryInfo(Integer milestoneId, String releaseTag) { this.milestoneId = milestoneId; this.releaseTag = releaseTag; } public Integer getMilestoneId() { return milestoneId; } public void setMilestoneId(Integer milestoneId) { this.milestoneId = milestoneId; } public String getReleaseTag() { return releaseTag; } public void setReleaseTag(String releaseTag) { this.releaseTag = releaseTag; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/info/BuildInfo.java
src/main/java/org/ohdsi/webapi/info/BuildInfo.java
package org.ohdsi.webapi.info; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.info.BuildProperties; import org.springframework.stereotype.Component; import java.util.Optional; @Component public class BuildInfo { private final String artifactVersion; private final String build; private final String timestamp; private final String branch; private final String commitId; private final RepositoryInfo atlasRepositoryInfo; private final RepositoryInfo webapiRepositoryInfo; public BuildInfo(BuildProperties buildProperties, @Value("${build.number}") final String buildNumber) { this.artifactVersion = String.format("%s %s", buildProperties.getArtifact(), buildProperties.getVersion()); this.build = buildNumber; this.timestamp = buildProperties.getTime().toString(); this.branch = buildProperties.get("git.branch"); this.commitId = buildProperties.get("git.commit.id"); this.atlasRepositoryInfo = new RepositoryInfo( getAsInteger(buildProperties, "atlas.milestone.id"), buildProperties.get("atlas.release.tag") ); this.webapiRepositoryInfo = new RepositoryInfo( getAsInteger(buildProperties, "webapi.milestone.id"), buildProperties.get("webapi.release.tag") ); } private Integer getAsInteger(BuildProperties properties, String key) { String value = properties.get(key); return Optional.ofNullable(value).map(v -> { try { return StringUtils.isNotBlank(v) ? Integer.valueOf(v) : null; } catch (NumberFormatException e) { return null; } }).orElse(null); } public String getArtifactVersion() { return artifactVersion; } public String getBuild() { return build; } public String getTimestamp() { return timestamp; } public String getCommitId() { return commitId; } public String getBranch() { return branch; } public RepositoryInfo getAtlasRepositoryInfo() { return atlasRepositoryInfo; } public RepositoryInfo getWebapiRepositoryInfo() { return webapiRepositoryInfo; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/info/InfoService.java
src/main/java/org/ohdsi/webapi/info/InfoService.java
/* * Copyright 2019 Observational Health Data Sciences and Informatics [OHDSI.org]. * * 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. * * Authors: Christopher Knoll, Pavel Grafkin */ package org.ohdsi.webapi.info; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.commons.lang3.StringUtils; import org.ohdsi.info.ConfigurationInfo; import org.springframework.boot.info.BuildProperties; import org.springframework.stereotype.Controller; import java.util.List; import java.util.stream.Collectors; @Path("/info") @Controller public class InfoService { private final Info info; public InfoService(BuildProperties buildProperties, BuildInfo buildInfo, List<ConfigurationInfo> configurationInfoList) { String version = getVersion(buildProperties); this.info = new Info( version, buildInfo, configurationInfoList.stream().collect(Collectors.toMap(ConfigurationInfo::getKey, ConfigurationInfo::getProperties)) ); } /** * Get info about the WebAPI instance */ @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) public Info getInfo() { return info; } private String getVersion(BuildProperties buildProperties) { return StringUtils.split(buildProperties.getVersion(), '-')[0]; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/achilles/service/AchillesCacheService.java
src/main/java/org/ohdsi/webapi/achilles/service/AchillesCacheService.java
package org.ohdsi.webapi.achilles.service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.ohdsi.webapi.achilles.domain.AchillesCacheEntity; import org.ohdsi.webapi.achilles.repository.AchillesCacheRepository; import org.ohdsi.webapi.shiro.management.datasource.SourceAccessor; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @Service public class AchillesCacheService { private static final Logger LOG = LoggerFactory.getLogger(AchillesCacheService.class); private final AchillesCacheRepository cacheRepository; private final ObjectMapper objectMapper; @Value("${spring.jpa.properties.hibernate.jdbc.batch_size}") private int batchSize; @Autowired private SourceRepository sourceRepository; @Autowired private SourceAccessor sourceAccessor; public AchillesCacheService(AchillesCacheRepository cacheRepository, ObjectMapper objectMapper) { this.cacheRepository = cacheRepository; this.objectMapper = objectMapper; } @Transactional(readOnly = true) public AchillesCacheEntity getCache(Source source, String cacheName) { return cacheRepository.findBySourceAndCacheName(source, cacheName); } @Transactional(readOnly = true) public List<AchillesCacheEntity> findBySourceAndNames(Source source, List<String> names) { return cacheRepository.findBySourceAndNames(source, names); } @Transactional(propagation = Propagation.REQUIRES_NEW) public AchillesCacheEntity createCache(Source source, String cacheName, Object result) throws JsonProcessingException { AchillesCacheEntity cacheEntity = getCache(source, cacheName); String cache = objectMapper.writeValueAsString(result); if (Objects.nonNull(cacheEntity)) { cacheEntity.setCache(cache); } else { cacheEntity = new AchillesCacheEntity(); cacheEntity.setSource(source); cacheEntity.setCacheName(cacheName); cacheEntity.setCache(cache); } return cacheRepository.save(cacheEntity); } @Transactional(propagation = Propagation.REQUIRES_NEW) public void saveDrilldownCacheMap(Source source, String domain, Map<Integer, ObjectNode> conceptNodes) { if (conceptNodes.isEmpty()) { // nothing to cache LOG.warn( "Cannot cache drilldown reports for {}, domain {}. Check if result schema contains achilles results tables.", source.getSourceKey(), domain); return; } Map<String, ObjectNode> nodes = new HashMap<>(batchSize); for (Map.Entry<Integer, ObjectNode> entry : conceptNodes.entrySet()) { if (nodes.size() >= batchSize) { createCacheEntities(source, nodes); nodes.clear(); } Integer key = entry.getKey(); String cacheName = getCacheName(domain, key); nodes.put(cacheName, entry.getValue()); } createCacheEntities(source, nodes); nodes.clear(); } @Transactional() public void clearCache() { List<Source> sources = sourceRepository.findAll(); sources.stream().forEach(this::clearCache); } @Transactional() public void clearCache(Source source) { if (sourceAccessor.hasAccess(source)) { cacheRepository.deleteBySource(source); } } private void createCacheEntities(Source source, Map<String, ObjectNode> nodes) { List<AchillesCacheEntity> cacheEntities = getEntities(source, nodes); cacheRepository.save(cacheEntities); } private List<AchillesCacheEntity> getEntities(Source source, Map<String, ObjectNode> nodes) { List<String> cacheNames = new ArrayList<>(nodes.keySet()); List<AchillesCacheEntity> cacheEntities = findBySourceAndNames(source, cacheNames); nodes.forEach((key, value) -> { // check if the entity with given cache name already exists Optional<AchillesCacheEntity> cacheEntity = cacheEntities.stream() .filter(entity -> entity.getCacheName().equals(key)) .findAny(); try { String newValue = objectMapper.writeValueAsString(value); if (cacheEntity.isPresent()) { // if cache entity already exists update its value cacheEntity.get().setCache(newValue); } else { // if cache entity does not exist - create new one AchillesCacheEntity newEntity = new AchillesCacheEntity(); newEntity.setCacheName(key); newEntity.setSource(source); newEntity.setCache(newValue); cacheEntities.add(newEntity); } } catch (JsonProcessingException e) { throw new RuntimeException(e); } }); return cacheEntities; } private String getCacheName(String domain, int conceptId) { return String.format("drilldown_%s_%d", domain, conceptId); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/achilles/domain/AchillesCacheEntity.java
src/main/java/org/ohdsi/webapi/achilles/domain/AchillesCacheEntity.java
package org.ohdsi.webapi.achilles.domain; import org.ohdsi.webapi.source.Source; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "achilles_cache") public class AchillesCacheEntity { @Id @SequenceGenerator(name = "achilles_cache_seq", sequenceName = "achilles_cache_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "achilles_cache_seq") private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "source_id") private Source source; @Column(name = "cache_name", nullable = false) private String cacheName; @Column(name = "cache") private String cache; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Source getSource() { return source; } public void setSource(Source source) { this.source = source; } public String getCacheName() { return cacheName; } public void setCacheName(String cacheName) { this.cacheName = cacheName; } public String getCache() { return cache; } public void setCache(String cacheName) { this.cache = cacheName; } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/achilles/repository/AchillesCacheRepository.java
src/main/java/org/ohdsi/webapi/achilles/repository/AchillesCacheRepository.java
package org.ohdsi.webapi.achilles.repository; import org.ohdsi.webapi.achilles.domain.AchillesCacheEntity; import org.ohdsi.webapi.source.Source; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface AchillesCacheRepository extends CrudRepository<AchillesCacheEntity, Long> { AchillesCacheEntity findBySourceAndCacheName(Source source, String type); @Query("select ac from AchillesCacheEntity ac where source = :source and cacheName in :names") List<AchillesCacheEntity> findBySourceAndNames(@Param("source") Source source, @Param("names") List<String> names); @Modifying @Query("delete from AchillesCacheEntity where source = :source") void deleteBySource(@Param("source") Source source); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/achilles/aspect/AchillesCache.java
src/main/java/org/ohdsi/webapi/achilles/aspect/AchillesCache.java
package org.ohdsi.webapi.achilles.aspect; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface AchillesCache { String value(); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/achilles/aspect/AchillesCacheAspect.java
src/main/java/org/ohdsi/webapi/achilles/aspect/AchillesCacheAspect.java
package org.ohdsi.webapi.achilles.aspect; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.ohdsi.webapi.achilles.domain.AchillesCacheEntity; import org.ohdsi.webapi.achilles.service.AchillesCacheService; import org.ohdsi.webapi.source.Source; import org.ohdsi.webapi.source.SourceRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; @Aspect @Component public class AchillesCacheAspect { private static final Logger LOG = LoggerFactory.getLogger(AchillesCacheAspect.class); private final SourceRepository sourceRepository; private final ObjectMapper objectMapper; private final AchillesCacheService cacheService; public AchillesCacheAspect(SourceRepository sourceRepository, ObjectMapper objectMapper, AchillesCacheService cacheService) { this.sourceRepository = sourceRepository; this.objectMapper = objectMapper; this.cacheService = cacheService; } @Pointcut("@annotation(AchillesCache)") public void cachePointcut() { } @Around("cachePointcut()") public Object cache(ProceedingJoinPoint joinPoint) throws Throwable { String cacheName = getCacheName(joinPoint); String sourceKey = getParams(joinPoint).get("sourceKey"); try { Source source = getSource(Objects.requireNonNull(sourceKey)); AchillesCacheEntity cacheEntity = cacheService.getCache(Objects.requireNonNull(source), cacheName); if (Objects.isNull(cacheEntity)) { Object result = joinPoint.proceed(); try { cacheEntity = cacheService.createCache(source, cacheName, result); } catch (DataIntegrityViolationException e) { // cache can be created during executing join point, try to get it again cacheEntity = cacheService.getCache(Objects.requireNonNull(source), cacheName); } } return objectMapper.readValue(cacheEntity.getCache(), getReturnType(joinPoint)); } catch (Exception e) { LOG.error("exception during getting cache " + cacheName + " for source " + sourceKey, e); // ignore exception and call join point return joinPoint.proceed(); } } private Class<?> getReturnType(ProceedingJoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); return ((MethodSignature) signature).getReturnType(); } private Source getSource(String sourceKey) { return sourceRepository.findBySourceKey(sourceKey); } private String getAnnotationValue(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); return method.getAnnotation(AchillesCache.class).value(); } private String getCacheName(JoinPoint joinPoint) { String cachePrefix = getAnnotationValue(joinPoint); Map<String, String> params = getParams(joinPoint); String paramNamePart = params.entrySet().stream() .filter(entry -> !"sourceKey".equals(entry.getKey())) .map(Map.Entry::getValue) .collect(Collectors.joining("_")); return cachePrefix + (StringUtils.isEmpty(paramNamePart) ? "" : "_" + paramNamePart); } private Map<String, String> getParams(JoinPoint joinPoint) { String[] names = ((MethodSignature) joinPoint.getSignature()).getParameterNames(); Object[] objects = joinPoint.getArgs(); return IntStream.range(0, names.length) .boxed() .collect(Collectors.toMap(i -> names[i], i -> String.valueOf(objects[i]))); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/tool/ToolService.java
src/main/java/org/ohdsi/webapi/tool/ToolService.java
package org.ohdsi.webapi.tool; import org.ohdsi.webapi.tool.dto.ToolDTO; import java.util.List; public interface ToolService { List<ToolDTO> getTools(); ToolDTO saveTool(ToolDTO toolDTO); ToolDTO getById(Integer id); void delete(Integer id); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/tool/ToolRepository.java
src/main/java/org/ohdsi/webapi/tool/ToolRepository.java
package org.ohdsi.webapi.tool; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ToolRepository extends JpaRepository<Tool, Integer> { List<Tool> findAllByEnabled(boolean enabled); }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/tool/ToolServiceImpl.java
src/main/java/org/ohdsi/webapi/tool/ToolServiceImpl.java
package org.ohdsi.webapi.tool; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.shiro.SecurityUtils; import org.ohdsi.webapi.service.AbstractDaoService; import org.ohdsi.webapi.shiro.Entities.UserEntity; import org.ohdsi.webapi.tool.dto.ToolDTO; import org.springframework.stereotype.Service; @Service public class ToolServiceImpl extends AbstractDaoService implements ToolService { private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; private final ToolRepository toolRepository; public ToolServiceImpl(ToolRepository toolRepository) { this.toolRepository = toolRepository; } @Override public List<ToolDTO> getTools() { List<Tool> tools = (isAdmin() || canManageTools()) ? toolRepository.findAll() : toolRepository.findAllByEnabled(true); return tools.stream() .map(this::toDTO).collect(Collectors.toList()); } @Override public ToolDTO saveTool(ToolDTO toolDTO) { Tool tool = saveToolFromDTO(toolDTO, getCurrentUser()); return toDTO(toolRepository.saveAndFlush(tool)); } private Tool saveToolFromDTO(ToolDTO toolDTO, UserEntity currentUser) { Tool tool = toEntity(toolDTO); if (toolDTO.getId() == null) { tool.setCreatedBy(currentUser); } tool.setModifiedBy(currentUser); return tool; } @Override public ToolDTO getById(Integer id) { return toDTO(toolRepository.findOne(id)); } @Override public void delete(Integer id) { toolRepository.delete(id); } private boolean canManageTools() { return Stream.of("tool:put", "tool:post", "tool:*:delete") .allMatch(permission -> SecurityUtils.getSubject().isPermitted(permission)); } Tool toEntity(ToolDTO toolDTO) { boolean isNewTool = toolDTO.getId() == null; Tool tool = isNewTool ? new Tool() : toolRepository.findOne(toolDTO.getId()); Instant currentInstant = Instant.now(); if (isNewTool) { setCreationDetails(tool, currentInstant); } else { setModificationDetails(tool, currentInstant); } updateToolFromDTO(tool, toolDTO); return tool; } private void setCreationDetails(Tool tool, Instant currentInstant) { tool.setCreatedDate(Date.from(currentInstant)); tool.setCreatedBy(getCurrentUser()); } private void setModificationDetails(Tool tool, Instant currentInstant) { tool.setModifiedDate(Date.from(currentInstant)); tool.setModifiedBy(getCurrentUser()); } private void updateToolFromDTO(Tool tool, ToolDTO toolDTO) { Optional.ofNullable(toolDTO.getName()).ifPresent(tool::setName); Optional.ofNullable(toolDTO.getUrl()).ifPresent(tool::setUrl); Optional.ofNullable(toolDTO.getDescription()).ifPresent(tool::setDescription); Optional.ofNullable(toolDTO.getEnabled()).ifPresent(tool::setEnabled); } ToolDTO toDTO(Tool tool) { return Optional.ofNullable(tool) .map(t -> { ToolDTO toolDTO = new ToolDTO(); toolDTO.setId(t.getId()); toolDTO.setName(t.getName()); toolDTO.setUrl(t.getUrl()); toolDTO.setDescription(t.getDescription()); Optional.ofNullable(tool.getCreatedBy()) .map(UserEntity::getId) .map(userRepository::findOne) .map(UserEntity::getName) .ifPresent(toolDTO::setCreatedByName); Optional.ofNullable(tool.getModifiedBy()) .map(UserEntity::getId) .map(userRepository::findOne) .map(UserEntity::getName) .ifPresent(toolDTO::setModifiedByName); toolDTO.setCreatedDate(t.getCreatedDate() != null ? new SimpleDateFormat(DATE_TIME_FORMAT).format(t.getCreatedDate()) : null); toolDTO.setModifiedDate(t.getModifiedDate() != null ? new SimpleDateFormat(DATE_TIME_FORMAT).format(t.getModifiedDate()) : null); toolDTO.setEnabled(t.getEnabled()); return toolDTO; }) .orElse(null); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/tool/ToolController.java
src/main/java/org/ohdsi/webapi/tool/ToolController.java
package org.ohdsi.webapi.tool; import org.ohdsi.webapi.tool.dto.ToolDTO; import org.springframework.stereotype.Controller; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; @Controller @Path("/tool") public class ToolController { private final ToolServiceImpl service; public ToolController(ToolServiceImpl service) { this.service = service; } @GET @Path("") @Produces(MediaType.APPLICATION_JSON) public List<ToolDTO> getTools() { return service.getTools(); } @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public ToolDTO getToolById(@PathParam("id") Integer id) { return service.getById(id); } @POST @Path("") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public ToolDTO createTool(ToolDTO dto) { return service.saveTool(dto); } @DELETE @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public void delete(@PathParam("id") Integer id) { service.delete(id); } @PUT @Path("") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public ToolDTO updateTool(ToolDTO toolDTO) { return service.saveTool(toolDTO); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/tool/Tool.java
src/main/java/org/ohdsi/webapi/tool/Tool.java
package org.ohdsi.webapi.tool; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.ohdsi.webapi.model.CommonEntity; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.Column; import java.util.Objects; @Entity @Table(name = "tool") public class Tool extends CommonEntity<Integer> { @Id @GenericGenerator( name = "tool_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "tool_seq"), @Parameter(name = "increment_size", value = "1") } ) @GeneratedValue(generator = "tool_generator") private Integer id; @Column(name = "name") private String name; @Column(name = "url") private String url; @Column(name = "description") private String description; @Column(name = "is_enabled") private Boolean enabled; @Override public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tool tool = (Tool) o; return Objects.equals(name, tool.name); } @Override public int hashCode() { return Objects.hash(name); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/tool/dto/ToolDTO.java
src/main/java/org/ohdsi/webapi/tool/dto/ToolDTO.java
package org.ohdsi.webapi.tool.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.ohdsi.webapi.shiro.Entities.UserEntity; import java.util.Objects; @JsonIgnoreProperties(ignoreUnknown = true) public class ToolDTO { private Integer id; private String name; private String url; private String description; private String createdByName; private String modifiedByName; private String createdDate; private String modifiedDate; private Boolean isEnabled; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCreatedByName() { return createdByName; } public void setCreatedByName(String createdByName) { this.createdByName = createdByName; } public String getModifiedByName() { return modifiedByName; } public void setModifiedByName(String modifiedByName) { this.modifiedByName = modifiedByName; } public String getCreatedDate() { return createdDate; } public void setCreatedDate(String createdDate) { this.createdDate = createdDate; } public String getModifiedDate() { return modifiedDate; } public void setModifiedDate(String modifiedDate) { this.modifiedDate = modifiedDate; } public Boolean getEnabled() { return isEnabled; } public void setEnabled(Boolean enabled) { isEnabled = enabled; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ToolDTO toolDTO = (ToolDTO) o; return Objects.equals(name, toolDTO.name); } @Override public int hashCode() { return Objects.hash(name); } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/therapy/TherapyPathReport.java
src/main/java/org/ohdsi/webapi/therapy/TherapyPathReport.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ohdsi.webapi.therapy; /** * * @author fdefalco */ public class TherapyPathReport { public int reportId; public String reportCaption; public String year; public String disease; public String datasource; }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/therapy/TherapyPathVector.java
src/main/java/org/ohdsi/webapi/therapy/TherapyPathVector.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ohdsi.webapi.therapy; /** * * @author fdefalco */ public class TherapyPathVector { public String key; public int count; }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/ohdsi/webapi/therapy/TherapySummary.java
src/main/java/org/ohdsi/webapi/therapy/TherapySummary.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ohdsi.webapi.therapy; /** * * @author fdefalco */ public class TherapySummary { public String key; public String name; public int tx1; public int tx2; public int tx3; public int total; }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
OHDSI/WebAPI
https://github.com/OHDSI/WebAPI/blob/b22d7bf02d98c0cf78c46801877368d6ecad2245/src/main/java/org/pac4j/oidc/profile/converter/OidcLongTimeConverter.java
src/main/java/org/pac4j/oidc/profile/converter/OidcLongTimeConverter.java
/* * * Copyright 2017 Observational Health Data Sciences and Informatics * 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. * * Authors: Mikhail Mironov * */ package org.pac4j.oidc.profile.converter; import org.pac4j.core.exception.TechnicalException; import org.pac4j.core.profile.converter.AttributeConverter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class OidcLongTimeConverter implements AttributeConverter<Date> { public OidcLongTimeConverter() { } public Date convert(Object attribute) { if (attribute instanceof Long) { long milliseconds = (Long) attribute * 1000L; return new Date(milliseconds); } else if (attribute instanceof String) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'"); try { return sdf.parse((String)attribute); } catch (ParseException var4) { throw new TechnicalException(var4); } } else { return attribute instanceof Date ? (Date)attribute : null; } } }
java
Apache-2.0
b22d7bf02d98c0cf78c46801877368d6ecad2245
2026-01-05T02:37:20.475642Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/library/src/main/java/com/crossbowffs/remotepreferences/RemoteUtils.java
library/src/main/java/com/crossbowffs/remotepreferences/RemoteUtils.java
package com.crossbowffs.remotepreferences; import java.util.HashSet; import java.util.Set; /** * Common utilities used to serialize and deserialize * preferences between the preference provider and caller. */ /* package */ final class RemoteUtils { private RemoteUtils() {} /** * Casts the parameter to a string set. Useful to avoid the unchecked * warning that would normally come with the cast. The value must * already be a string set; this does not deserialize it. * * @param value The value, as type {@link Object}. * @return The value, as type {@link Set<String>}. */ @SuppressWarnings("unchecked") public static Set<String> castStringSet(Object value) { return (Set<String>)value; } /** * Returns the {@code TYPE_*} constant corresponding to the given * object's type. * * @param value The original object. * @return One of the {@link RemoteContract}{@code .TYPE_*} constants. */ public static int getPreferenceType(Object value) { if (value == null) return RemoteContract.TYPE_NULL; if (value instanceof String) return RemoteContract.TYPE_STRING; if (value instanceof Set<?>) return RemoteContract.TYPE_STRING_SET; if (value instanceof Integer) return RemoteContract.TYPE_INT; if (value instanceof Long) return RemoteContract.TYPE_LONG; if (value instanceof Float) return RemoteContract.TYPE_FLOAT; if (value instanceof Boolean) return RemoteContract.TYPE_BOOLEAN; throw new AssertionError("Unknown preference type: " + value.getClass()); } /** * Serializes the specified object to a format that is safe to use * with {@link android.content.ContentValues}. To recover the original * object, use {@link #deserializeInput(Object, int)}. * * @param value The object to serialize. * @return The serialized object. */ public static Object serializeOutput(Object value) { if (value instanceof Boolean) { return serializeBoolean((Boolean)value); } else if (value instanceof Set<?>) { return serializeStringSet(castStringSet(value)); } else { return value; } } /** * Deserializes an object that was serialized using * {@link #serializeOutput(Object)}. If the expected type does * not match the actual type of the object, a {@link ClassCastException} * will be thrown. * * @param value The object to deserialize. * @param expectedType The expected type of the deserialized object. * @return The deserialized object. */ public static Object deserializeInput(Object value, int expectedType) { if (expectedType == RemoteContract.TYPE_NULL) { if (value != null) { throw new IllegalArgumentException("Expected null, got non-null value"); } else { return null; } } try { switch (expectedType) { case RemoteContract.TYPE_STRING: return (String)value; case RemoteContract.TYPE_STRING_SET: return deserializeStringSet((String)value); case RemoteContract.TYPE_INT: return (Integer)value; case RemoteContract.TYPE_LONG: return (Long)value; case RemoteContract.TYPE_FLOAT: return (Float)value; case RemoteContract.TYPE_BOOLEAN: return deserializeBoolean(value); } } catch (ClassCastException e) { throw new IllegalArgumentException("Expected type " + expectedType + ", got " + value.getClass(), e); } throw new IllegalArgumentException("Unknown type: " + expectedType); } /** * Serializes a {@link Boolean} to a format that is safe to use * with {@link android.content.ContentValues}. * * @param value The {@link Boolean} to serialize. * @return 1 if {@code value} is {@code true}, 0 if {@code value} is {@code false}. */ private static Integer serializeBoolean(Boolean value) { if (value == null) { return null; } else { return value ? 1 : 0; } } /** * Deserializes a {@link Boolean} that was serialized using * {@link #serializeBoolean(Boolean)}. * * @param value The {@link Boolean} to deserialize. * @return {@code true} if {@code value} is 1, {@code false} if {@code value} is 0. */ private static Boolean deserializeBoolean(Object value) { if (value == null) { return null; } else if (value instanceof Boolean) { return (Boolean)value; } else { return (Integer)value != 0; } } /** * Serializes a {@link Set<String>} to a format that is safe to use * with {@link android.content.ContentValues}. * * @param stringSet The {@link Set<String>} to serialize. * @return The serialized string set. */ public static String serializeStringSet(Set<String> stringSet) { if (stringSet == null) { return null; } StringBuilder sb = new StringBuilder(); for (String s : stringSet) { sb.append(s.replace("\\", "\\\\").replace(";", "\\;")); sb.append(';'); } return sb.toString(); } /** * Deserializes a {@link Set<String>} that was serialized using * {@link #serializeStringSet(Set)}. * * @param serializedString The {@link Set<String>} to deserialize. * @return The deserialized string set. */ public static Set<String> deserializeStringSet(String serializedString) { if (serializedString == null) { return null; } HashSet<String> stringSet = new HashSet<String>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < serializedString.length(); ++i) { char c = serializedString.charAt(i); if (c == '\\') { char next = serializedString.charAt(++i); sb.append(next); } else if (c == ';') { stringSet.add(sb.toString()); sb.delete(0, sb.length()); } else { sb.append(c); } } // We require that the serialized string ends with a ; per element // since that's how we distinguish empty sets from sets containing // an empty string. Assume caller is doing unsafe string joins // instead of using the serializeStringSet API, and fail fast. if (sb.length() != 0) { throw new IllegalArgumentException("Serialized string set contains trailing chars"); } return stringSet; } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferencePath.java
library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferencePath.java
package com.crossbowffs.remotepreferences; /** * A path consists of a preference file name and optionally a key within * the preference file. The key will be set for operations that involve * a single preference (e.g. {@code getInt}), and {@code null} for operations * on an entire preference file (e.g. {@code getAll}). */ /* package */ class RemotePreferencePath { public final String fileName; public final String key; public RemotePreferencePath(String prefFileName, String prefKey) { this.fileName = prefFileName; this.key = prefKey; } public RemotePreferencePath withKey(String prefKey) { if (this.key != null) { throw new IllegalArgumentException("Path already has a key"); } return new RemotePreferencePath(this.fileName, prefKey); } @Override public String toString() { String ret = "file:" + this.fileName; if (this.key != null) { ret += "/key:" + this.key; } return ret; } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/library/src/main/java/com/crossbowffs/remotepreferences/RemoteContract.java
library/src/main/java/com/crossbowffs/remotepreferences/RemoteContract.java
package com.crossbowffs.remotepreferences; /** * Constants used for communicating with the preference provider. */ /* package */ final class RemoteContract { public static final String COLUMN_KEY = "key"; public static final String COLUMN_TYPE = "type"; public static final String COLUMN_VALUE = "value"; public static final String[] COLUMN_ALL = { RemoteContract.COLUMN_KEY, RemoteContract.COLUMN_TYPE, RemoteContract.COLUMN_VALUE }; public static final int TYPE_NULL = 0; public static final int TYPE_STRING = 1; public static final int TYPE_STRING_SET = 2; public static final int TYPE_INT = 3; public static final int TYPE_LONG = 4; public static final int TYPE_FLOAT = 5; public static final int TYPE_BOOLEAN = 6; private RemoteContract() {} }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferenceUriParser.java
library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferenceUriParser.java
package com.crossbowffs.remotepreferences; import android.content.UriMatcher; import android.net.Uri; import java.util.List; /** * Decodes URIs passed between {@link RemotePreferences} and {@link RemotePreferenceProvider}. */ /* package */ class RemotePreferenceUriParser { private static final int PREFERENCES_ID = 1; private static final int PREFERENCE_ID = 2; private final UriMatcher mUriMatcher; public RemotePreferenceUriParser(String authority) { mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); mUriMatcher.addURI(authority, "*/", PREFERENCES_ID); mUriMatcher.addURI(authority, "*/*", PREFERENCE_ID); } /** * Parses the preference file and key from a query URI. If the key * is not specified, the returned path will contain {@code null} as the key. * * @param uri The URI to parse. * @return A path object containing the preference file name and key. */ public RemotePreferencePath parse(Uri uri) { int match = mUriMatcher.match(uri); if (match != PREFERENCE_ID && match != PREFERENCES_ID) { throw new IllegalArgumentException("Invalid URI: " + uri); } // The URI must fall under one of these patterns: // // content://authority/prefFileName/prefKey // content://authority/prefFileName/ // content://authority/prefFileName // // The match ID will be PREFERENCE_ID under the first case, // and PREFERENCES_ID under the second and third cases // (UriMatcher ignores trailing slashes). List<String> pathSegments = uri.getPathSegments(); String prefFileName = pathSegments.get(0); String prefKey = null; if (match == PREFERENCE_ID) { prefKey = pathSegments.get(1); } return new RemotePreferencePath(prefFileName, prefKey); } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferenceFile.java
library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferenceFile.java
package com.crossbowffs.remotepreferences; /** * Represents a single preference file and the information needed to * access that preference file. */ public class RemotePreferenceFile { private final String mFileName; private final boolean mIsDeviceProtected; /** * Initializes the preference file information. If you are targeting Android * N or above and the preference needs to be accessed before the first unlock, * set {@code isDeviceProtected} to {@code true}. * * @param fileName Name of the preference file. * @param isDeviceProtected {@code true} if the preference file is device protected, * {@code false} if it is credential protected. */ public RemotePreferenceFile(String fileName, boolean isDeviceProtected) { mFileName = fileName; mIsDeviceProtected = isDeviceProtected; } /** * Initializes the preference file information. Assumes the preferences are * located in credential protected storage. * * @param fileName Name of the preference file. */ public RemotePreferenceFile(String fileName) { this(fileName, false); } /** * Returns the name of the preference file. * * @return The name of the preference file. */ public String getFileName() { return mFileName; } /** * Returns whether the preferences are located in device protected storage. * * @return {@code true} if the preference file is device protected, * {@code false} if it is credential protected. */ public boolean isDeviceProtected() { return mIsDeviceProtected; } /** * Converts an array of preference file names to {@link RemotePreferenceFile} * objects. Assumes all preference files are NOT in device protected storage. * * @param prefFileNames The names of the preference files to expose. * @return An array of {@link RemotePreferenceFile} objects. */ public static RemotePreferenceFile[] fromFileNames(String[] prefFileNames) { RemotePreferenceFile[] prefFiles = new RemotePreferenceFile[prefFileNames.length]; for (int i = 0; i < prefFileNames.length; i++) { prefFiles[i] = new RemotePreferenceFile(prefFileNames[i]); } return prefFiles; } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferences.java
library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferences.java
package com.crossbowffs.remotepreferences; import android.annotation.TargetApi; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Handler; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; /** * <p> * Provides a {@link SharedPreferences} compatible API to * {@link RemotePreferenceProvider}. See {@link RemotePreferenceProvider} * for more information. * </p> * * <p> * If you are reading preferences from the same context as the * provider, you should not use this class; just access the * {@link SharedPreferences} API as you would normally. * </p> */ public class RemotePreferences implements SharedPreferences { private final Context mContext; private final Handler mHandler; private final Uri mBaseUri; private final boolean mStrictMode; private final WeakHashMap<OnSharedPreferenceChangeListener, PreferenceContentObserver> mListeners; private final RemotePreferenceUriParser mUriParser; /** * Initializes a new remote preferences object, with strict * mode disabled. * * @param context Used to access the preference provider. * @param authority The authority of the preference provider. * @param prefFileName The name of the preference file to access. */ public RemotePreferences(Context context, String authority, String prefFileName) { this(context, authority, prefFileName, false); } /** * Initializes a new remote preferences object. If {@code strictMode} * is {@code true} and the remote preference provider cannot be accessed, * read/write operations on this object will throw a * {@link RemotePreferenceAccessException}. Otherwise, default values * will be returned. * * @param context Used to access the preference provider. * @param authority The authority of the preference provider. * @param prefFileName The name of the preference file to access. * @param strictMode Whether strict mode is enabled. */ public RemotePreferences(Context context, String authority, String prefFileName, boolean strictMode) { this(context, new Handler(context.getMainLooper()), authority, prefFileName, strictMode); } /** * Initializes a new remote preferences object. If {@code strictMode} * is {@code true} and the remote preference provider cannot be accessed, * read/write operations on this object will throw a * {@link RemotePreferenceAccessException}. Otherwise, default values * will be returned. * * @param context Used to access the preference provider. * @param handler Used to receive preference change events. * @param authority The authority of the preference provider. * @param prefFileName The name of the preference file to access. * @param strictMode Whether strict mode is enabled. */ /* package */ RemotePreferences(Context context, Handler handler, String authority, String prefFileName, boolean strictMode) { checkNotNull("context", context); checkNotNull("handler", handler); checkNotNull("authority", authority); checkNotNull("prefFileName", prefFileName); mContext = context; mHandler = handler; mBaseUri = Uri.parse("content://" + authority).buildUpon().appendPath(prefFileName).build(); mStrictMode = strictMode; mListeners = new WeakHashMap<OnSharedPreferenceChangeListener, PreferenceContentObserver>(); mUriParser = new RemotePreferenceUriParser(authority); } @Override public Map<String, ?> getAll() { return queryAll(); } @Override public String getString(String key, String defValue) { return (String)querySingle(key, defValue, RemoteContract.TYPE_STRING); } @Override @TargetApi(11) public Set<String> getStringSet(String key, Set<String> defValues) { if (Build.VERSION.SDK_INT < 11) { throw new UnsupportedOperationException("String sets only supported on API 11 and above"); } return RemoteUtils.castStringSet(querySingle(key, defValues, RemoteContract.TYPE_STRING_SET)); } @Override public int getInt(String key, int defValue) { return (Integer)querySingle(key, defValue, RemoteContract.TYPE_INT); } @Override public long getLong(String key, long defValue) { return (Long)querySingle(key, defValue, RemoteContract.TYPE_LONG); } @Override public float getFloat(String key, float defValue) { return (Float)querySingle(key, defValue, RemoteContract.TYPE_FLOAT); } @Override public boolean getBoolean(String key, boolean defValue) { return (Boolean)querySingle(key, defValue, RemoteContract.TYPE_BOOLEAN); } @Override public boolean contains(String key) { return containsKey(key); } @Override public Editor edit() { return new RemotePreferencesEditor(); } @Override public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { checkNotNull("listener", listener); if (mListeners.containsKey(listener)) return; PreferenceContentObserver observer = new PreferenceContentObserver(listener); mListeners.put(listener, observer); mContext.getContentResolver().registerContentObserver(mBaseUri, true, observer); } @Override public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { checkNotNull("listener", listener); PreferenceContentObserver observer = mListeners.remove(listener); if (observer != null) { mContext.getContentResolver().unregisterContentObserver(observer); } } /** * If {@code object} is {@code null}, throws an exception. * * @param name The name of the object, for use in the exception message. * @param object The object to check. */ private static void checkNotNull(String name, Object object) { if (object == null) { throw new IllegalArgumentException(name + " is null"); } } /** * If {@code key} is {@code null} or {@code ""}, throws an exception. * * @param key The object to check. */ private static void checkKeyNotEmpty(String key) { if (key == null || key.length() == 0) { throw new IllegalArgumentException("Key is null or empty"); } } /** * If strict mode is enabled, wraps and throws the given exception. * Otherwise, does nothing. * * @param e The exception to wrap. */ private void wrapException(Exception e) { if (mStrictMode) { throw new RemotePreferenceAccessException(e); } } /** * Queries the specified URI. If the query fails and strict mode is * enabled, an exception will be thrown; otherwise {@code null} will * be returned. * * @param uri The URI to query. * @param columns The columns to include in the returned cursor. * @return A cursor used to access the queried preference data. */ private Cursor query(Uri uri, String[] columns) { Cursor cursor = null; try { cursor = mContext.getContentResolver().query(uri, columns, null, null, null); } catch (Exception e) { wrapException(e); } if (cursor == null && mStrictMode) { throw new RemotePreferenceAccessException("query() failed or returned null cursor"); } return cursor; } /** * Writes multiple preferences at once to the preference provider. * If the operation fails and strict mode is enabled, an exception * will be thrown; otherwise {@code false} will be returned. * * @param uri The URI to modify. * @param values The values to write. * @return Whether the operation succeeded. */ private boolean bulkInsert(Uri uri, ContentValues[] values) { int count; try { count = mContext.getContentResolver().bulkInsert(uri, values); } catch (Exception e) { wrapException(e); return false; } if (count != values.length && mStrictMode) { throw new RemotePreferenceAccessException("bulkInsert() failed"); } return count == values.length; } /** * Reads a single preference from the preference provider. This may * throw a {@link ClassCastException} even if strict mode is disabled * if the provider returns an incompatible type. If strict mode is * disabled and the preference cannot be read, the default value is returned. * * @param key The preference key to read. * @param defValue The default value, if there is no existing value. * @param expectedType The expected type of the value. * @return The value of the preference, or {@code defValue} if no value exists. */ private Object querySingle(String key, Object defValue, int expectedType) { checkKeyNotEmpty(key); Uri uri = mBaseUri.buildUpon().appendPath(key).build(); String[] columns = {RemoteContract.COLUMN_TYPE, RemoteContract.COLUMN_VALUE}; Cursor cursor = query(uri, columns); try { if (cursor == null || !cursor.moveToFirst()) { return defValue; } int typeCol = cursor.getColumnIndexOrThrow(RemoteContract.COLUMN_TYPE); int type = cursor.getInt(typeCol); if (type == RemoteContract.TYPE_NULL) { return defValue; } else if (type != expectedType) { throw new ClassCastException("Preference type mismatch"); } int valueCol = cursor.getColumnIndexOrThrow(RemoteContract.COLUMN_VALUE); return getValue(cursor, typeCol, valueCol); } finally { if (cursor != null) { cursor.close(); } } } /** * Reads all preferences from the preference provider. If strict * mode is disabled and the preferences cannot be read, an empty * map is returned. * * @return A map containing all preferences. */ private Map<String, Object> queryAll() { Uri uri = mBaseUri.buildUpon().appendPath("").build(); String[] columns = {RemoteContract.COLUMN_KEY, RemoteContract.COLUMN_TYPE, RemoteContract.COLUMN_VALUE}; Cursor cursor = query(uri, columns); try { HashMap<String, Object> map = new HashMap<String, Object>(); if (cursor == null) { return map; } int keyCol = cursor.getColumnIndexOrThrow(RemoteContract.COLUMN_KEY); int typeCol = cursor.getColumnIndexOrThrow(RemoteContract.COLUMN_TYPE); int valueCol = cursor.getColumnIndexOrThrow(RemoteContract.COLUMN_VALUE); while (cursor.moveToNext()) { String key = cursor.getString(keyCol); map.put(key, getValue(cursor, typeCol, valueCol)); } return map; } finally { if (cursor != null) { cursor.close(); } } } /** * Checks whether the preference exists. If strict mode is * disabled and the preferences cannot be read, {@code false} * is returned. * * @param key The key to check existence for. * @return Whether the preference exists. */ private boolean containsKey(String key) { checkKeyNotEmpty(key); Uri uri = mBaseUri.buildUpon().appendPath(key).build(); String[] columns = {RemoteContract.COLUMN_TYPE}; Cursor cursor = query(uri, columns); try { if (cursor == null || !cursor.moveToFirst()) { return false; } int typeCol = cursor.getColumnIndexOrThrow(RemoteContract.COLUMN_TYPE); return cursor.getInt(typeCol) != RemoteContract.TYPE_NULL; } finally { if (cursor != null) { cursor.close(); } } } /** * Extracts a preference value from a cursor. Performs deserialization * of the value if necessary. * * @param cursor The cursor containing the preference value. * @param typeCol The index containing the {@link RemoteContract#COLUMN_TYPE} column. * @param valueCol The index containing the {@link RemoteContract#COLUMN_VALUE} column. * @return The value from the cursor. */ private Object getValue(Cursor cursor, int typeCol, int valueCol) { int expectedType = cursor.getInt(typeCol); switch (expectedType) { case RemoteContract.TYPE_STRING: return cursor.getString(valueCol); case RemoteContract.TYPE_STRING_SET: return RemoteUtils.deserializeStringSet(cursor.getString(valueCol)); case RemoteContract.TYPE_INT: return cursor.getInt(valueCol); case RemoteContract.TYPE_LONG: return cursor.getLong(valueCol); case RemoteContract.TYPE_FLOAT: return cursor.getFloat(valueCol); case RemoteContract.TYPE_BOOLEAN: return cursor.getInt(valueCol) != 0; default: throw new AssertionError("Invalid expected type: " + expectedType); } } /** * Implementation of the {@link SharedPreferences.Editor} interface * for use with RemotePreferences. */ private class RemotePreferencesEditor implements Editor { private final ArrayList<ContentValues> mValues = new ArrayList<ContentValues>(); /** * Creates a new {@link ContentValues} with the specified key and * type columns pre-filled. The {@link RemoteContract#COLUMN_VALUE} * field is NOT filled in. * * @param key The preference key. * @param type The preference type. * @return The pre-filled values. */ private ContentValues createContentValues(String key, int type) { ContentValues values = new ContentValues(4); values.put(RemoteContract.COLUMN_KEY, key); values.put(RemoteContract.COLUMN_TYPE, type); return values; } /** * Creates an operation to add/set a new preference. Again, the * {@link RemoteContract#COLUMN_VALUE} field is NOT filled in. * This will also add the values to the operation queue. * * @param key The preference key to add. * @param type The preference type to add. * @return The pre-filled values. */ private ContentValues createAddOp(String key, int type) { checkKeyNotEmpty(key); ContentValues values = createContentValues(key, type); mValues.add(values); return values; } /** * Creates an operation to delete a preference. All fields * are pre-filled. This will also add the values to the * operation queue. * * @param key The preference key to delete. * @return The pre-filled values. */ private ContentValues createRemoveOp(String key) { // Note: Remove operations are inserted at the beginning // of the list (this preserves the SharedPreferences behavior // that all removes are performed before any adds) ContentValues values = createContentValues(key, RemoteContract.TYPE_NULL); values.putNull(RemoteContract.COLUMN_VALUE); mValues.add(0, values); return values; } @Override public Editor putString(String key, String value) { createAddOp(key, RemoteContract.TYPE_STRING).put(RemoteContract.COLUMN_VALUE, value); return this; } @Override @TargetApi(11) public Editor putStringSet(String key, Set<String> value) { if (Build.VERSION.SDK_INT < 11) { throw new UnsupportedOperationException("String sets only supported on API 11 and above"); } String serializedSet = RemoteUtils.serializeStringSet(value); createAddOp(key, RemoteContract.TYPE_STRING_SET).put(RemoteContract.COLUMN_VALUE, serializedSet); return this; } @Override public Editor putInt(String key, int value) { createAddOp(key, RemoteContract.TYPE_INT).put(RemoteContract.COLUMN_VALUE, value); return this; } @Override public Editor putLong(String key, long value) { createAddOp(key, RemoteContract.TYPE_LONG).put(RemoteContract.COLUMN_VALUE, value); return this; } @Override public Editor putFloat(String key, float value) { createAddOp(key, RemoteContract.TYPE_FLOAT).put(RemoteContract.COLUMN_VALUE, value); return this; } @Override public Editor putBoolean(String key, boolean value) { createAddOp(key, RemoteContract.TYPE_BOOLEAN).put(RemoteContract.COLUMN_VALUE, value ? 1 : 0); return this; } @Override public Editor remove(String key) { checkKeyNotEmpty(key); createRemoveOp(key); return this; } @Override public Editor clear() { createRemoveOp(""); return this; } @Override public boolean commit() { ContentValues[] values = mValues.toArray(new ContentValues[mValues.size()]); Uri uri = mBaseUri.buildUpon().appendPath("").build(); return bulkInsert(uri, values); } @Override public void apply() { commit(); } } /** * {@link ContentObserver} subclass used to monitor preference changes * in the remote preference provider. When a change is detected, this will notify * the corresponding {@link SharedPreferences.OnSharedPreferenceChangeListener}. */ private class PreferenceContentObserver extends ContentObserver { private final WeakReference<OnSharedPreferenceChangeListener> mListener; private PreferenceContentObserver(OnSharedPreferenceChangeListener listener) { super(mHandler); mListener = new WeakReference<OnSharedPreferenceChangeListener>(listener); } @Override public boolean deliverSelfNotifications() { return true; } @Override public void onChange(boolean selfChange, Uri uri) { RemotePreferencePath path = mUriParser.parse(uri); // We use a weak reference to mimic the behavior of SharedPreferences. // The code which registered the listener is responsible for holding a // reference to it. If at any point we find that the listener has been // garbage collected, we unregister the observer. OnSharedPreferenceChangeListener listener = mListener.get(); if (listener == null) { mContext.getContentResolver().unregisterContentObserver(this); } else { listener.onSharedPreferenceChanged(RemotePreferences.this, path.key); } } } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferenceAccessException.java
library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferenceAccessException.java
package com.crossbowffs.remotepreferences; /** * Thrown if the preference provider could not be accessed. * This is commonly thrown under these conditions: * <ul> * <li>Preference provider component is disabled</li> * <li>Preference provider denied access via {@link RemotePreferenceProvider#checkAccess(String, String, boolean)}</li> * <li>Insufficient permissions to access provider (via {@code AndroidManifest.xml})</li> * <li>Incorrect provider authority/file name passed to constructor</li> * </ul> */ public class RemotePreferenceAccessException extends RuntimeException { public RemotePreferenceAccessException() { } public RemotePreferenceAccessException(String detailMessage) { super(detailMessage); } public RemotePreferenceAccessException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } public RemotePreferenceAccessException(Throwable throwable) { super(throwable); } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferenceProvider.java
library/src/main/java/com/crossbowffs/remotepreferences/RemotePreferenceProvider.java
package com.crossbowffs.remotepreferences; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.ContentObserver; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.os.Build; import java.util.HashMap; import java.util.Map; /** * <p> * Exposes {@link SharedPreferences} to other apps running on the device. * </p> * * <p> * You must extend this class and declare a 0-argument constructor which * calls the super constructor with the appropriate authority and * preference file name parameters. Remember to add your provider to * your {@code AndroidManifest.xml} file and set the {@code android:exported} * property to true. * </p> * * <p> * For granular access control, override {@link #checkAccess(String, String, boolean)} * and return {@code false} to deny the operation. * </p> * * <p> * To access the data from a remote process, use {@link RemotePreferences} * initialized with the same authority and the desired preference file name. * You may also manually query the provider; here are some example queries * and their equivalent {@link SharedPreferences} API calls: * </p> * * <pre> * query(uri = content://authority/foo/bar) * = getSharedPreferences("foo").get("bar") * * query(uri = content://authority/foo) * = getSharedPreferences("foo").getAll() * * insert(uri = content://authority/foo/bar, values = [{type = TYPE_STRING, value = "baz"}]) * = getSharedPreferences("foo").edit().putString("bar", "baz").commit() * * insert(uri = content://authority/foo, values = [{key = "bar", type = TYPE_STRING, value = "baz"}]) * = getSharedPreferences("foo").edit().putString("bar", "baz").commit() * * delete(uri = content://authority/foo/bar) * = getSharedPreferences("foo").edit().remove("bar").commit() * * delete(uri = content://authority/foo) * = getSharedPreferences("foo").edit().clear().commit() * </pre> * * <p> * Also note that if you are querying string sets, they will be returned * in a serialized form: {@code ["foo;bar", "baz"]} is converted to * {@code "foo\\;bar;baz;"} (note the trailing semicolon). Booleans are * converted into integers: 1 for true, 0 for false. This is only applicable * if you are using raw queries; all of these subtleties are transparently * handled by {@link RemotePreferences}. * </p> */ public abstract class RemotePreferenceProvider extends ContentProvider implements SharedPreferences.OnSharedPreferenceChangeListener { private final Uri mBaseUri; private final RemotePreferenceFile[] mPrefFiles; private final Map<String, SharedPreferences> mPreferences; private final RemotePreferenceUriParser mUriParser; /** * Initializes the remote preference provider with the specified * authority and preference file names. The authority must match the * {@code android:authorities} property defined in your manifest * file. Only the specified preference files will be accessible * through the provider. This constructor assumes all preferences * are located in credential protected storage; if you are using * device protected storage, use * {@link #RemotePreferenceProvider(String, RemotePreferenceFile[])}. * * @param authority The authority of the provider. * @param prefFileNames The names of the preference files to expose. */ public RemotePreferenceProvider(String authority, String[] prefFileNames) { this(authority, RemotePreferenceFile.fromFileNames(prefFileNames)); } /** * Initializes the remote preference provider with the specified * authority and preference files. The authority must match the * {@code android:authorities} property defined in your manifest * file. Only the specified preference files will be accessible * through the provider. * * @param authority The authority of the provider. * @param prefFiles The preference files to expose. */ public RemotePreferenceProvider(String authority, RemotePreferenceFile[] prefFiles) { mBaseUri = Uri.parse("content://" + authority); mPrefFiles = prefFiles; mPreferences = new HashMap<String, SharedPreferences>(prefFiles.length); mUriParser = new RemotePreferenceUriParser(authority); } /** * Checks whether the specified preference is accessible by callers. * The default implementation returns {@code true} for all accesses. * You may override this method to control which preferences can be * read or written. Note that {@code prefKey} will be {@code ""} when * accessing an entire file, so a whitelist is strongly recommended * over a blacklist (your default case should be {@code return false}, * not {@code return true}). * * @param prefFileName The name of the preference file. * @param prefKey The preference key. This is an empty string when handling the * {@link SharedPreferences#getAll()} and * {@link SharedPreferences.Editor#clear()} operations. * @param write {@code true} for put/remove/clear operations; {@code false} for get operations. * @return {@code true} if the access is allowed; {@code false} otherwise. */ protected boolean checkAccess(String prefFileName, String prefKey, boolean write) { return true; } /** * Called at application startup to register preference change listeners. * * @return Always returns {@code true}. */ @Override public boolean onCreate() { // We register the shared preference listeners whenever the provider // is created. This method is called before almost all other code in // the app, which ensures that we never miss a preference change. for (RemotePreferenceFile file : mPrefFiles) { Context context = getContext(); if (file.isDeviceProtected() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { context = context.createDeviceProtectedStorageContext(); } SharedPreferences prefs = getSharedPreferences(context, file.getFileName()); prefs.registerOnSharedPreferenceChangeListener(this); mPreferences.put(file.getFileName(), prefs); } return true; } /** * Generate {@link SharedPreferences} to store the key-value data. * Override this method to provide a custom implementation of {@link SharedPreferences}. * * @param context The context that should be used to get the preferences object. * @param prefFileName The name of the preference file. * @return An object implementing the {@link SharedPreferences} interface. */ protected SharedPreferences getSharedPreferences(Context context, String prefFileName) { return context.getSharedPreferences(prefFileName, Context.MODE_PRIVATE); } /** * Returns a cursor for the specified preference(s). If {@code uri} * is in the form {@code content://authority/prefFileName/prefKey}, the * cursor will contain a single row containing the queried preference. * If {@code uri} is in the form {@code content://authority/prefFileName}, * the cursor will contain one row for each preference in the specified * file. * * @param uri Specifies the preference file and key (optional) to query. * @param projection Specifies which fields should be returned in the cursor. * @param selection Ignored. * @param selectionArgs Ignored. * @param sortOrder Ignored. * @return A cursor used to access the queried preference data. */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { RemotePreferencePath prefPath = mUriParser.parse(uri); SharedPreferences prefs = getSharedPreferencesOrThrow(prefPath, false); Map<String, ?> prefMap = prefs.getAll(); // If no projection is specified, we return all columns. if (projection == null) { projection = RemoteContract.COLUMN_ALL; } // Fill out the cursor with the preference data. If the caller // didn't ask for a particular preference, we return all of them. MatrixCursor cursor = new MatrixCursor(projection); if (isSingleKey(prefPath.key)) { Object prefValue = prefMap.get(prefPath.key); cursor.addRow(buildRow(projection, prefPath.key, prefValue)); } else { for (Map.Entry<String, ?> entry : prefMap.entrySet()) { String prefKey = entry.getKey(); Object prefValue = entry.getValue(); cursor.addRow(buildRow(projection, prefKey, prefValue)); } } return cursor; } /** * Not used in RemotePreferences. Always returns {@code null}. * * @param uri Ignored. * @return Always returns {@code null}. */ @Override public String getType(Uri uri) { return null; } /** * Writes the value of the specified preference(s). If no key is specified, * {@link RemoteContract#COLUMN_TYPE} must be equal to {@link RemoteContract#TYPE_NULL}, * representing the {@link SharedPreferences.Editor#clear()} operation. * * @param uri Specifies the preference file and key (optional) to write. * @param values Specifies the key (optional), type and value of the preference to write. * @return A URI representing the preference written, or {@code null} on failure. */ @Override public Uri insert(Uri uri, ContentValues values) { if (values == null) { return null; } RemotePreferencePath prefPath = mUriParser.parse(uri); String prefKey = getKeyFromUriOrValues(prefPath, values); SharedPreferences prefs = getSharedPreferencesOrThrow(prefPath, true); SharedPreferences.Editor editor = prefs.edit(); putPreference(editor, prefKey, values); if (editor.commit()) { return getPreferenceUri(prefPath.fileName, prefKey); } else { return null; } } /** * Writes multiple preference values at once. {@code uri} must * be in the form {@code content://authority/prefFileName}. See * {@link #insert(Uri, ContentValues)} for more information. * * @param uri Specifies the preference file to write to. * @param values See {@link #insert(Uri, ContentValues)}. * @return The number of preferences written, or 0 on failure. */ @Override public int bulkInsert(Uri uri, ContentValues[] values) { RemotePreferencePath prefPath = mUriParser.parse(uri); if (isSingleKey(prefPath.key)) { throw new IllegalArgumentException("Cannot bulk insert with single key URI"); } SharedPreferences prefs = getSharedPreferencesByName(prefPath.fileName); SharedPreferences.Editor editor = prefs.edit(); for (ContentValues value : values) { String prefKey = getKeyFromValues(value); checkAccessOrThrow(prefPath.withKey(prefKey), true); putPreference(editor, prefKey, value); } if (editor.commit()) { return values.length; } else { return 0; } } /** * Deletes the specified preference(s). If {@code uri} is in the form * {@code content://authority/prefFileName/prefKey}, this will only delete * the one preference specified in the URI; if {@code uri} is in the form * {@code content://authority/prefFileName}, clears all preferences. * * @param uri Specifies the preference file and key (optional) to delete. * @param selection Ignored. * @param selectionArgs Ignored. * @return 1 if the preferences committed successfully, or 0 on failure. */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { RemotePreferencePath prefPath = mUriParser.parse(uri); SharedPreferences prefs = getSharedPreferencesOrThrow(prefPath, true); SharedPreferences.Editor editor = prefs.edit(); if (isSingleKey(prefPath.key)) { editor.remove(prefPath.key); } else { editor.clear(); } // There's no reliable method of getting the actual number of // preference values changed, so callers should not rely on this // value. A return value of 1 means success, 0 means failure. if (editor.commit()) { return 1; } else { return 0; } } /** * Updates the value of the specified preference(s). This is a wrapper * around {@link #insert(Uri, ContentValues)} if {@code values} is not * {@code null}, or {@link #delete(Uri, String, String[])} if {@code values} * is {@code null}. * * @param uri Specifies the preference file and key (optional) to update. * @param values {@code null} to delete the preference, * @param selection Ignored. * @param selectionArgs Ignored. * @return 1 if the preferences committed successfully, or 0 on failure. */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (values == null) { return delete(uri, selection, selectionArgs); } else { return insert(uri, values) != null ? 1 : 0; } } /** * Listener for preference value changes in the local application. * Re-raises the event through the * {@link ContentResolver#notifyChange(Uri, ContentObserver)} API * to any registered {@link ContentObserver} objects. Note that this * is NOT called for {@link SharedPreferences.Editor#clear()}. * * @param prefs The preference file that changed. * @param prefKey The preference key that changed. */ @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String prefKey) { RemotePreferenceFile prefFile = getSharedPreferencesFile(prefs); Uri uri = getPreferenceUri(prefFile.getFileName(), prefKey); Context context = getContext(); if (prefFile.isDeviceProtected() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { context = context.createDeviceProtectedStorageContext(); } ContentResolver resolver = context.getContentResolver(); resolver.notifyChange(uri, null); } /** * Writes the value of the specified preference(s). If {@code prefKey} * is empty, {@code values} must contain {@link RemoteContract#TYPE_NULL} * for the type, representing the {@link SharedPreferences.Editor#clear()} * operation. * * @param editor The preference file to modify. * @param prefKey The preference key to modify, or {@code null} for the entire file. * @param values The values to write. */ private void putPreference(SharedPreferences.Editor editor, String prefKey, ContentValues values) { // Get the new value type. Note that we manually check // for null, then unbox the Integer so we don't cause a NPE. Integer type = values.getAsInteger(RemoteContract.COLUMN_TYPE); if (type == null) { throw new IllegalArgumentException("Invalid or no preference type specified"); } // deserializeInput makes sure the actual object type matches // the expected type, so we must perform this step before actually // performing any actions. Object rawValue = values.get(RemoteContract.COLUMN_VALUE); Object value = RemoteUtils.deserializeInput(rawValue, type); // If we are writing to the "directory" and the type is null, // then we should clear the preferences. if (!isSingleKey(prefKey)) { if (type == RemoteContract.TYPE_NULL) { editor.clear(); return; } else { throw new IllegalArgumentException("Attempting to insert preference with null or empty key"); } } switch (type) { case RemoteContract.TYPE_NULL: editor.remove(prefKey); break; case RemoteContract.TYPE_STRING: editor.putString(prefKey, (String)value); break; case RemoteContract.TYPE_STRING_SET: if (Build.VERSION.SDK_INT >= 11) { editor.putStringSet(prefKey, RemoteUtils.castStringSet(value)); } else { throw new IllegalArgumentException("String set preferences not supported on API < 11"); } break; case RemoteContract.TYPE_INT: editor.putInt(prefKey, (Integer)value); break; case RemoteContract.TYPE_LONG: editor.putLong(prefKey, (Long)value); break; case RemoteContract.TYPE_FLOAT: editor.putFloat(prefKey, (Float)value); break; case RemoteContract.TYPE_BOOLEAN: editor.putBoolean(prefKey, (Boolean)value); break; default: throw new IllegalArgumentException("Cannot set preference with type " + type); } } /** * Used to project a preference value to the schema requested by the caller. * * @param projection The projection requested by the caller. * @param key The preference key. * @param value The preference value. * @return A row representing the preference using the given schema. */ private Object[] buildRow(String[] projection, String key, Object value) { Object[] row = new Object[projection.length]; for (int i = 0; i < row.length; ++i) { String col = projection[i]; if (RemoteContract.COLUMN_KEY.equals(col)) { row[i] = key; } else if (RemoteContract.COLUMN_TYPE.equals(col)) { row[i] = RemoteUtils.getPreferenceType(value); } else if (RemoteContract.COLUMN_VALUE.equals(col)) { row[i] = RemoteUtils.serializeOutput(value); } else { throw new IllegalArgumentException("Invalid column name: " + col); } } return row; } /** * Returns whether the specified key represents a single preference key * (as opposed to the entire preference file). * * @param prefKey The preference key to check. * @return Whether the key refers to a single preference. */ private static boolean isSingleKey(String prefKey) { return prefKey != null; } /** * Parses the preference key from {@code values}. If the key is not * specified in the values, {@code null} is returned. * * @param values The query values to parse. * @return The parsed key, or {@code null} if no key was found. */ private static String getKeyFromValues(ContentValues values) { String key = values.getAsString(RemoteContract.COLUMN_KEY); if (key != null && key.length() == 0) { key = null; } return key; } /** * Parses the preference key from the specified sources. Since there * are two ways to specify the key (from the URI or from the query values), * the only allowed combinations are: * * uri.key == values.key * uri.key != null and values.key == null = URI key is used * uri.key == null and values.key != null = values key is used * uri.key == null and values.key == null = no key * * If none of these conditions are met, an exception is thrown. * * @param prefPath Parsed URI key from {@code mUriParser.parse(uri)}. * @param values Query values provided by the caller. * @return The parsed key, or {@code null} if the key refers to a preference file. */ private static String getKeyFromUriOrValues(RemotePreferencePath prefPath, ContentValues values) { String uriKey = prefPath.key; String valuesKey = getKeyFromValues(values); if (isSingleKey(uriKey) && isSingleKey(valuesKey)) { // If a key is specified in both the URI and // ContentValues, they must match if (!uriKey.equals(valuesKey)) { throw new IllegalArgumentException("Conflicting keys specified in URI and ContentValues"); } return uriKey; } else if (isSingleKey(uriKey)) { return uriKey; } else if (isSingleKey(valuesKey)) { return valuesKey; } else { return null; } } /** * Checks that the caller has permissions to access the specified preference. * Throws an exception if permission is denied. * * @param prefPath The preference file and key to be accessed. * @param write Whether the operation will modify the preference. */ private void checkAccessOrThrow(RemotePreferencePath prefPath, boolean write) { // For backwards compatibility, checkAccess takes an empty string when // referring to the whole file. String prefKey = prefPath.key; if (!isSingleKey(prefKey)) { prefKey = ""; } if (!checkAccess(prefPath.fileName, prefKey, write)) { throw new SecurityException("Insufficient permissions to access: " + prefPath); } } /** * Returns the {@link SharedPreferences} instance with the specified name. * This is essentially equivalent to {@link Context#getSharedPreferences(String, int)}, * except that it will used the internally cached version, and throws an * exception if the provider was not configured to access that preference file. * * @param prefFileName The name of the preference file to access. * @return The {@link SharedPreferences} instance with the specified file name. */ private SharedPreferences getSharedPreferencesByName(String prefFileName) { SharedPreferences prefs = mPreferences.get(prefFileName); if (prefs == null) { throw new IllegalArgumentException("Unknown preference file name: " + prefFileName); } return prefs; } /** * Returns the file name for a {@link SharedPreferences} instance. * Throws an exception if the provider was not configured to access * the specified preferences. * * @param prefs The shared preferences object. * @return The name of the preference file. */ private String getSharedPreferencesFileName(SharedPreferences prefs) { for (Map.Entry<String, SharedPreferences> entry : mPreferences.entrySet()) { if (entry.getValue() == prefs) { return entry.getKey(); } } throw new IllegalArgumentException("Unknown preference file"); } /** * Get the corresponding {@link RemotePreferenceFile} object for a * {@link SharedPreferences} instance. Throws an exception if the * provider was not configured to access the specified preferences. * * @param prefs The shared preferences object. * @return The corresponding {@link RemotePreferenceFile} object. */ private RemotePreferenceFile getSharedPreferencesFile(SharedPreferences prefs) { String prefFileName = getSharedPreferencesFileName(prefs); for (RemotePreferenceFile file : mPrefFiles) { if (file.getFileName().equals(prefFileName)) { return file; } } throw new IllegalArgumentException("Unknown preference file"); } /** * Returns the {@link SharedPreferences} instance with the specified name, * checking that the caller has permissions to access the specified key within * that file. If not, an exception will be thrown. * * @param prefPath The preference file and key to be accessed. * @param write Whether the operation will modify the preference. * @return The {@link SharedPreferences} instance with the specified file name. */ private SharedPreferences getSharedPreferencesOrThrow(RemotePreferencePath prefPath, boolean write) { checkAccessOrThrow(prefPath, write); return getSharedPreferencesByName(prefPath.fileName); } /** * Builds a URI for the specified preference file and key that can be used * to later query the same preference. * * @param prefFileName The preference file. * @param prefKey The preference key. * @return A URI representing the specified preference. */ private Uri getPreferenceUri(String prefFileName, String prefKey) { Uri.Builder builder = mBaseUri.buildUpon().appendPath(prefFileName); if (isSingleKey(prefKey)) { builder.appendPath(prefKey); } return builder.build(); } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/testapp/src/main/java/com/crossbowffs/remotepreferences/testapp/TestConstants.java
testapp/src/main/java/com/crossbowffs/remotepreferences/testapp/TestConstants.java
package com.crossbowffs.remotepreferences.testapp; public final class TestConstants { private TestConstants() {} public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".preferences"; public static final String AUTHORITY_DISABLED = BuildConfig.APPLICATION_ID + ".preferences.disabled"; public static final String PREF_FILE = "main_prefs"; public static final String UNREADABLE_PREF_KEY = "cannot_read_me"; public static final String UNWRITABLE_PREF_KEY = "cannot_write_me"; }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/testapp/src/main/java/com/crossbowffs/remotepreferences/testapp/TestPreferenceListener.java
testapp/src/main/java/com/crossbowffs/remotepreferences/testapp/TestPreferenceListener.java
package com.crossbowffs.remotepreferences.testapp; import android.content.SharedPreferences; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class TestPreferenceListener implements SharedPreferences.OnSharedPreferenceChangeListener { private boolean mIsCalled; private String mKey; private final CountDownLatch mLatch; public TestPreferenceListener() { mIsCalled = false; mKey = null; mLatch = new CountDownLatch(1); } public boolean isCalled() { return mIsCalled; } public String getKey() { if (!mIsCalled) { throw new IllegalStateException("Listener was not called"); } return mKey; } public boolean waitForChange(long seconds) { try { return mLatch.await(seconds, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new IllegalStateException("Listener wait was interrupted"); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { mIsCalled = true; mKey = key; mLatch.countDown(); } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/testapp/src/main/java/com/crossbowffs/remotepreferences/testapp/TestPreferenceProviderDisabled.java
testapp/src/main/java/com/crossbowffs/remotepreferences/testapp/TestPreferenceProviderDisabled.java
package com.crossbowffs.remotepreferences.testapp; import com.crossbowffs.remotepreferences.RemotePreferenceProvider; public class TestPreferenceProviderDisabled extends RemotePreferenceProvider { public TestPreferenceProviderDisabled() { super(TestConstants.AUTHORITY_DISABLED, new String[] {TestConstants.PREF_FILE}); } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/testapp/src/main/java/com/crossbowffs/remotepreferences/testapp/TestPreferenceProvider.java
testapp/src/main/java/com/crossbowffs/remotepreferences/testapp/TestPreferenceProvider.java
package com.crossbowffs.remotepreferences.testapp; import com.crossbowffs.remotepreferences.RemotePreferenceProvider; public class TestPreferenceProvider extends RemotePreferenceProvider { public TestPreferenceProvider() { super(TestConstants.AUTHORITY, new String[] {TestConstants.PREF_FILE}); } @Override protected boolean checkAccess(String prefName, String prefKey, boolean write) { if (prefKey.equals(TestConstants.UNREADABLE_PREF_KEY) && !write) return false; if (prefKey.equals(TestConstants.UNWRITABLE_PREF_KEY) && write) return false; return true; } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/testapp/src/androidTest/java/com/crossbowffs/remotepreferences/RemotePreferencesTest.java
testapp/src/androidTest/java/com/crossbowffs/remotepreferences/RemotePreferencesTest.java
package com.crossbowffs.remotepreferences; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.SdkSuppress; import androidx.test.platform.app.InstrumentationRegistry; import com.crossbowffs.remotepreferences.testapp.TestConstants; import com.crossbowffs.remotepreferences.testapp.TestPreferenceListener; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; import java.util.Map; @RunWith(AndroidJUnit4.class) public class RemotePreferencesTest { private Context getLocalContext() { return InstrumentationRegistry.getInstrumentation().getContext(); } private Context getRemoteContext() { return InstrumentationRegistry.getInstrumentation().getTargetContext(); } private SharedPreferences getSharedPreferences() { Context context = getRemoteContext(); return context.getSharedPreferences(TestConstants.PREF_FILE, Context.MODE_PRIVATE); } private RemotePreferences getRemotePreferences(boolean strictMode) { // This is not a typo! We are using the LOCAL context to initialize a REMOTE prefs // instance. This is the whole point of RemotePreferences! Context context = getLocalContext(); return new RemotePreferences(context, TestConstants.AUTHORITY, TestConstants.PREF_FILE, strictMode); } private RemotePreferences getDisabledRemotePreferences(boolean strictMode) { Context context = getLocalContext(); return new RemotePreferences(context, TestConstants.AUTHORITY_DISABLED, TestConstants.PREF_FILE, strictMode); } private RemotePreferences getRemotePreferencesWithHandler(Handler handler, boolean strictMode) { Context context = getLocalContext(); return new RemotePreferences(context, handler, TestConstants.AUTHORITY, TestConstants.PREF_FILE, strictMode); } @Before public void resetPreferences() { getSharedPreferences().edit().clear().commit(); } @Test public void testBasicRead() { getSharedPreferences() .edit() .putString("string", "foobar") .putInt("int", 0xeceb3026) .putFloat("float", 3.14f) .putBoolean("bool", true) .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); Assert.assertEquals("foobar", remotePrefs.getString("string", null)); Assert.assertEquals(0xeceb3026, remotePrefs.getInt("int", 0)); Assert.assertEquals(3.14f, remotePrefs.getFloat("float", 0f), 0.0); Assert.assertEquals(true, remotePrefs.getBoolean("bool", false)); } @Test public void testBasicWrite() { getRemotePreferences(true) .edit() .putString("string", "foobar") .putInt("int", 0xeceb3026) .putFloat("float", 3.14f) .putBoolean("bool", true) .apply(); SharedPreferences sharedPrefs = getSharedPreferences(); Assert.assertEquals("foobar", sharedPrefs.getString("string", null)); Assert.assertEquals(0xeceb3026, sharedPrefs.getInt("int", 0)); Assert.assertEquals(3.14f, sharedPrefs.getFloat("float", 0f), 0.0); Assert.assertEquals(true, sharedPrefs.getBoolean("bool", false)); } @Test public void testRemove() { getSharedPreferences() .edit() .putString("string", "foobar") .putInt("int", 0xeceb3026) .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); remotePrefs.edit().remove("string").apply(); Assert.assertEquals("default", remotePrefs.getString("string", "default")); Assert.assertEquals(0xeceb3026, remotePrefs.getInt("int", 0)); } @Test public void testClear() { SharedPreferences sharedPrefs = getSharedPreferences(); getSharedPreferences() .edit() .putString("string", "foobar") .putInt("int", 0xeceb3026) .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); remotePrefs.edit().clear().apply(); Assert.assertEquals(0, sharedPrefs.getAll().size()); Assert.assertEquals("default", remotePrefs.getString("string", "default")); Assert.assertEquals(0, remotePrefs.getInt("int", 0)); } @Test public void testGetAll() { getSharedPreferences() .edit() .putString("string", "foobar") .putInt("int", 0xeceb3026) .putFloat("float", 3.14f) .putBoolean("bool", true) .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); Map<String, ?> prefs = remotePrefs.getAll(); Assert.assertEquals("foobar", prefs.get("string")); Assert.assertEquals(0xeceb3026, prefs.get("int")); Assert.assertEquals(3.14f, prefs.get("float")); Assert.assertEquals(true, prefs.get("bool")); } @Test public void testContains() { getSharedPreferences() .edit() .putString("string", "foobar") .putInt("int", 0xeceb3026) .putFloat("float", 3.14f) .putBoolean("bool", true) .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); Assert.assertTrue(remotePrefs.contains("string")); Assert.assertTrue(remotePrefs.contains("int")); Assert.assertFalse(remotePrefs.contains("nonexistent")); } @Test public void testReadNonexistentPref() { RemotePreferences remotePrefs = getRemotePreferences(true); Assert.assertEquals("default", remotePrefs.getString("nonexistent_string", "default")); Assert.assertEquals(1337, remotePrefs.getInt("nonexistent_int", 1337)); } @Test public void testStringSetRead() { HashSet<String> set = new HashSet<>(); set.add("Chocola"); set.add("Vanilla"); set.add("Coconut"); set.add("Azuki"); set.add("Maple"); set.add("Cinnamon"); getSharedPreferences() .edit() .putStringSet("pref", set) .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); Assert.assertEquals(set, remotePrefs.getStringSet("pref", null)); } @Test public void testStringSetWrite() { HashSet<String> set = new HashSet<>(); set.add("Chocola"); set.add("Vanilla"); set.add("Coconut"); set.add("Azuki"); set.add("Maple"); set.add("Cinnamon"); getRemotePreferences(true) .edit() .putStringSet("pref", set) .apply(); SharedPreferences sharedPrefs = getSharedPreferences(); Assert.assertEquals(set, sharedPrefs.getStringSet("pref", null)); } @Test public void testEmptyStringSetRead() { HashSet<String> set = new HashSet<>(); getSharedPreferences() .edit() .putStringSet("pref", set) .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); Assert.assertEquals(set, remotePrefs.getStringSet("pref", null)); } @Test public void testEmptyStringSetWrite() { HashSet<String> set = new HashSet<>(); getRemotePreferences(true) .edit() .putStringSet("pref", set) .apply(); SharedPreferences sharedPrefs = getSharedPreferences(); Assert.assertEquals(set, sharedPrefs.getStringSet("pref", null)); } @Test public void testSetContainingEmptyStringRead() { HashSet<String> set = new HashSet<>(); set.add(""); getSharedPreferences() .edit() .putStringSet("pref", set) .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); Assert.assertEquals(set, remotePrefs.getStringSet("pref", null)); } @Test public void testSetContainingEmptyStringWrite() { HashSet<String> set = new HashSet<>(); set.add(""); getRemotePreferences(true) .edit() .putStringSet("pref", set) .apply(); SharedPreferences sharedPrefs = getSharedPreferences(); Assert.assertEquals(set, sharedPrefs.getStringSet("pref", null)); } @Test public void testReadStringAsStringSetFail() { getSharedPreferences() .edit() .putString("pref", "foo;bar;") .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); try { remotePrefs.getStringSet("pref", null); Assert.fail(); } catch (ClassCastException e) { // Expected } } @Test public void testReadStringSetAsStringFail() { HashSet<String> set = new HashSet<>(); set.add("foo"); set.add("bar"); getSharedPreferences() .edit() .putStringSet("pref", set) .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); try { remotePrefs.getString("pref", null); Assert.fail(); } catch (ClassCastException e) { // Expected } } @Test public void testReadBooleanAsIntFail() { getSharedPreferences() .edit() .putBoolean("pref", true) .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); try { remotePrefs.getInt("pref", 0); Assert.fail(); } catch (ClassCastException e) { // Expected } } @Test public void testReadIntAsBooleanFail() { getSharedPreferences() .edit() .putInt("pref", 42) .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); try { remotePrefs.getBoolean("pref", false); Assert.fail(); } catch (ClassCastException e) { // Expected } } @Test public void testInvalidAuthorityStrictMode() { Context context = getLocalContext(); RemotePreferences remotePrefs = new RemotePreferences(context, "foo", "bar", true); try { remotePrefs.getString("pref", null); Assert.fail(); } catch (RemotePreferenceAccessException e) { // Expected } } @Test public void testInvalidAuthorityNonStrictMode() { Context context = getLocalContext(); RemotePreferences remotePrefs = new RemotePreferences(context, "foo", "bar", false); Assert.assertEquals("default", remotePrefs.getString("pref", "default")); } @Test public void testDisabledProviderStrictMode() { RemotePreferences remotePrefs = getDisabledRemotePreferences(true); try { remotePrefs.getString("pref", null); Assert.fail(); } catch (RemotePreferenceAccessException e) { // Expected } } @Test public void testDisabledProviderNonStrictMode() { RemotePreferences remotePrefs = getDisabledRemotePreferences(false); Assert.assertEquals("default", remotePrefs.getString("pref", "default")); } @Test public void testUnreadablePrefStrictMode() { RemotePreferences remotePrefs = getRemotePreferences(true); try { remotePrefs.getString(TestConstants.UNREADABLE_PREF_KEY, null); Assert.fail(); } catch (RemotePreferenceAccessException e) { // Expected } } @Test public void testUnreadablePrefNonStrictMode() { RemotePreferences remotePrefs = getRemotePreferences(false); Assert.assertEquals("default", remotePrefs.getString(TestConstants.UNREADABLE_PREF_KEY, "default")); } @Test public void testUnwritablePrefStrictMode() { RemotePreferences remotePrefs = getRemotePreferences(true); try { remotePrefs.edit().putString(TestConstants.UNWRITABLE_PREF_KEY, "foobar").commit(); Assert.fail(); } catch (RemotePreferenceAccessException e) { // Expected } } @Test public void testUnwritablePrefNonStrictMode() { RemotePreferences remotePrefs = getRemotePreferences(false); Assert.assertFalse( remotePrefs .edit() .putString(TestConstants.UNWRITABLE_PREF_KEY, "foobar") .commit() ); } @Test public void testRemoveUnwritablePrefStrictMode() { getSharedPreferences() .edit() .putString(TestConstants.UNWRITABLE_PREF_KEY, "foobar") .apply(); RemotePreferences remotePrefs = getRemotePreferences(true); try { remotePrefs.edit().remove(TestConstants.UNWRITABLE_PREF_KEY).commit(); Assert.fail(); } catch (RemotePreferenceAccessException e) { // Expected } Assert.assertEquals("foobar", remotePrefs.getString(TestConstants.UNWRITABLE_PREF_KEY, "default")); } @Test public void testRemoveUnwritablePrefNonStrictMode() { getSharedPreferences() .edit() .putString(TestConstants.UNWRITABLE_PREF_KEY, "foobar") .apply(); RemotePreferences remotePrefs = getRemotePreferences(false); Assert.assertFalse(remotePrefs.edit().remove(TestConstants.UNWRITABLE_PREF_KEY).commit()); Assert.assertEquals("foobar", remotePrefs.getString(TestConstants.UNWRITABLE_PREF_KEY, "default")); } @Test public void testPreferenceChangeListener() { HandlerThread ht = new HandlerThread(getClass().getName()); try { ht.start(); Handler handler = new Handler(ht.getLooper()); RemotePreferences remotePrefs = getRemotePreferencesWithHandler(handler, true); TestPreferenceListener listener = new TestPreferenceListener(); try { remotePrefs.registerOnSharedPreferenceChangeListener(listener); getSharedPreferences() .edit() .putInt("foobar", 1337) .apply(); Assert.assertTrue(listener.waitForChange(1)); Assert.assertEquals("foobar", listener.getKey()); } finally { remotePrefs.unregisterOnSharedPreferenceChangeListener(listener); } } finally { ht.quit(); } } @Test @SdkSuppress(minSdkVersion = Build.VERSION_CODES.R) public void testPreferenceChangeListenerClear() { HandlerThread ht = new HandlerThread(getClass().getName()); try { ht.start(); Handler handler = new Handler(ht.getLooper()); RemotePreferences remotePrefs = getRemotePreferencesWithHandler(handler, true); TestPreferenceListener listener = new TestPreferenceListener(); try { remotePrefs.registerOnSharedPreferenceChangeListener(listener); getSharedPreferences() .edit() .clear() .apply(); Assert.assertTrue(listener.waitForChange(1)); Assert.assertNull(listener.getKey()); } finally { remotePrefs.unregisterOnSharedPreferenceChangeListener(listener); } } finally { ht.quit(); } } @Test public void testUnregisterPreferenceChangeListener() { HandlerThread ht = new HandlerThread(getClass().getName()); try { ht.start(); Handler handler = new Handler(ht.getLooper()); RemotePreferences remotePrefs = getRemotePreferencesWithHandler(handler, true); TestPreferenceListener listener = new TestPreferenceListener(); try { remotePrefs.registerOnSharedPreferenceChangeListener(listener); remotePrefs.unregisterOnSharedPreferenceChangeListener(listener); getSharedPreferences() .edit() .putInt("foobar", 1337) .apply(); Assert.assertFalse(listener.waitForChange(1)); } finally { remotePrefs.unregisterOnSharedPreferenceChangeListener(listener); } } finally { ht.quit(); } } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/testapp/src/androidTest/java/com/crossbowffs/remotepreferences/RemotePreferenceProviderTest.java
testapp/src/androidTest/java/com/crossbowffs/remotepreferences/RemotePreferenceProviderTest.java
package com.crossbowffs.remotepreferences; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.crossbowffs.remotepreferences.testapp.TestConstants; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; @RunWith(AndroidJUnit4.class) public class RemotePreferenceProviderTest { private Context getLocalContext() { return InstrumentationRegistry.getInstrumentation().getContext(); } private Context getRemoteContext() { return InstrumentationRegistry.getInstrumentation().getTargetContext(); } private SharedPreferences getSharedPreferences() { Context context = getRemoteContext(); return context.getSharedPreferences(TestConstants.PREF_FILE, Context.MODE_PRIVATE); } private Uri getQueryUri(String key) { String uri = "content://" + TestConstants.AUTHORITY + "/" + TestConstants.PREF_FILE; if (key != null) { uri += "/" + key; } return Uri.parse(uri); } @Before public void resetPreferences() { getSharedPreferences().edit().clear().commit(); } @Test public void testQueryAllPrefs() { getSharedPreferences() .edit() .putString("string", "foobar") .putInt("int", 1337) .apply(); ContentResolver resolver = getLocalContext().getContentResolver(); Cursor q = resolver.query(getQueryUri(null), null, null, null, null); Assert.assertEquals(2, q.getCount()); int key = q.getColumnIndex(RemoteContract.COLUMN_KEY); int type = q.getColumnIndex(RemoteContract.COLUMN_TYPE); int value = q.getColumnIndex(RemoteContract.COLUMN_VALUE); while (q.moveToNext()) { if (q.getString(key).equals("string")) { Assert.assertEquals(RemoteContract.TYPE_STRING, q.getInt(type)); Assert.assertEquals("foobar", q.getString(value)); } else if (q.getString(key).equals("int")) { Assert.assertEquals(RemoteContract.TYPE_INT, q.getInt(type)); Assert.assertEquals(1337, q.getInt(value)); } else { Assert.fail(); } } } @Test public void testQuerySinglePref() { getSharedPreferences() .edit() .putString("string", "foobar") .putInt("int", 1337) .apply(); ContentResolver resolver = getLocalContext().getContentResolver(); Cursor q = resolver.query(getQueryUri("string"), null, null, null, null); Assert.assertEquals(1, q.getCount()); int key = q.getColumnIndex(RemoteContract.COLUMN_KEY); int type = q.getColumnIndex(RemoteContract.COLUMN_TYPE); int value = q.getColumnIndex(RemoteContract.COLUMN_VALUE); q.moveToFirst(); Assert.assertEquals("string", q.getString(key)); Assert.assertEquals(RemoteContract.TYPE_STRING, q.getInt(type)); Assert.assertEquals("foobar", q.getString(value)); } @Test public void testQueryFailPermissionCheck() { getSharedPreferences() .edit() .putString(TestConstants.UNREADABLE_PREF_KEY, "foobar") .apply(); ContentResolver resolver = getLocalContext().getContentResolver(); try { resolver.query(getQueryUri(TestConstants.UNREADABLE_PREF_KEY), null, null, null, null); Assert.fail(); } catch (SecurityException e) { // Expected } } @Test public void testInsertPref() { ContentValues values = new ContentValues(); values.put(RemoteContract.COLUMN_KEY, "string"); values.put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING); values.put(RemoteContract.COLUMN_VALUE, "foobar"); ContentResolver resolver = getLocalContext().getContentResolver(); Uri uri = resolver.insert(getQueryUri(null), values); Assert.assertEquals(getQueryUri("string"), uri); SharedPreferences prefs = getSharedPreferences(); Assert.assertEquals("foobar", prefs.getString("string", null)); } @Test public void testInsertOverridePref() { SharedPreferences prefs = getSharedPreferences(); prefs .edit() .putString("string", "nyaa") .putInt("int", 1337) .apply(); ContentValues values = new ContentValues(); values.put(RemoteContract.COLUMN_KEY, "string"); values.put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING); values.put(RemoteContract.COLUMN_VALUE, "foobar"); ContentResolver resolver = getLocalContext().getContentResolver(); Uri uri = resolver.insert(getQueryUri(null), values); Assert.assertEquals(getQueryUri("string"), uri); Assert.assertEquals("foobar", prefs.getString("string", null)); Assert.assertEquals(1337, prefs.getInt("int", 0)); } @Test public void testInsertPrefKeyInUri() { ContentValues values = new ContentValues(); values.put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING); values.put(RemoteContract.COLUMN_VALUE, "foobar"); ContentResolver resolver = getLocalContext().getContentResolver(); Uri uri = resolver.insert(getQueryUri("string"), values); Assert.assertEquals(getQueryUri("string"), uri); SharedPreferences prefs = getSharedPreferences(); Assert.assertEquals("foobar", prefs.getString("string", null)); } @Test public void testInsertPrefKeyInUriAndValues() { ContentValues values = new ContentValues(); values.put(RemoteContract.COLUMN_KEY, "string"); values.put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING); values.put(RemoteContract.COLUMN_VALUE, "foobar"); ContentResolver resolver = getLocalContext().getContentResolver(); Uri uri = resolver.insert(getQueryUri("string"), values); Assert.assertEquals(getQueryUri("string"), uri); SharedPreferences prefs = getSharedPreferences(); Assert.assertEquals("foobar", prefs.getString("string", null)); } @Test public void testInsertPrefFailKeyInUriAndValuesMismatch() { ContentValues values = new ContentValues(); values.put(RemoteContract.COLUMN_KEY, "string"); values.put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING); values.put(RemoteContract.COLUMN_VALUE, "foobar"); ContentResolver resolver = getLocalContext().getContentResolver(); try { resolver.insert(getQueryUri("string2"), values); Assert.fail(); } catch (IllegalArgumentException e) { // Expected } SharedPreferences prefs = getSharedPreferences(); Assert.assertEquals("default", prefs.getString("string", "default")); } @Test public void testInsertMultiplePrefs() { ContentValues[] values = new ContentValues[2]; values[0] = new ContentValues(); values[0].put(RemoteContract.COLUMN_KEY, "string"); values[0].put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING); values[0].put(RemoteContract.COLUMN_VALUE, "foobar"); values[1] = new ContentValues(); values[1].put(RemoteContract.COLUMN_KEY, "int"); values[1].put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_INT); values[1].put(RemoteContract.COLUMN_VALUE, 1337); ContentResolver resolver = getLocalContext().getContentResolver(); int ret = resolver.bulkInsert(getQueryUri(null), values); Assert.assertEquals(2, ret); SharedPreferences prefs = getSharedPreferences(); Assert.assertEquals("foobar", prefs.getString("string", null)); Assert.assertEquals(1337, prefs.getInt("int", 0)); } @Test public void testInsertFailPermissionCheck() { ContentValues[] values = new ContentValues[2]; values[0] = new ContentValues(); values[0].put(RemoteContract.COLUMN_KEY, "string"); values[0].put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING); values[0].put(RemoteContract.COLUMN_VALUE, "foobar"); values[1] = new ContentValues(); values[1].put(RemoteContract.COLUMN_KEY, TestConstants.UNWRITABLE_PREF_KEY); values[1].put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_INT); values[1].put(RemoteContract.COLUMN_VALUE, 1337); ContentResolver resolver = getLocalContext().getContentResolver(); try { resolver.bulkInsert(getQueryUri(null), values); Assert.fail(); } catch (SecurityException e) { // Expected } SharedPreferences prefs = getSharedPreferences(); Assert.assertEquals("default", prefs.getString("string", "default")); Assert.assertEquals(0, prefs.getInt(TestConstants.UNWRITABLE_PREF_KEY, 0)); } @Test public void testInsertMultipleFailUriContainingKey() { ContentValues[] values = new ContentValues[1]; values[0] = new ContentValues(); values[0].put(RemoteContract.COLUMN_KEY, "string"); values[0].put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING); values[0].put(RemoteContract.COLUMN_VALUE, "foobar"); ContentResolver resolver = getLocalContext().getContentResolver(); try { resolver.bulkInsert(getQueryUri("key"), values); Assert.fail(); } catch (IllegalArgumentException e) { // Expected } SharedPreferences prefs = getSharedPreferences(); Assert.assertEquals("default", prefs.getString("string", "default")); } @Test public void testDeletePref() { SharedPreferences prefs = getSharedPreferences(); prefs .edit() .putString("string", "nyaa") .apply(); ContentResolver resolver = getLocalContext().getContentResolver(); resolver.delete(getQueryUri("string"), null, null); Assert.assertEquals("default", prefs.getString("string", "default")); } @Test public void testDeleteUnwritablePref() { SharedPreferences prefs = getSharedPreferences(); prefs .edit() .putString(TestConstants.UNWRITABLE_PREF_KEY, "nyaa") .apply(); ContentResolver resolver = getLocalContext().getContentResolver(); try { resolver.delete(getQueryUri(TestConstants.UNWRITABLE_PREF_KEY), null, null); Assert.fail(); } catch (SecurityException e) { // Expected } Assert.assertEquals("nyaa", prefs.getString(TestConstants.UNWRITABLE_PREF_KEY, "default")); } @Test public void testReadBoolean() { getSharedPreferences() .edit() .putBoolean("true", true) .putBoolean("false", false) .apply(); ContentResolver resolver = getLocalContext().getContentResolver(); Cursor q = resolver.query(getQueryUri(null), null, null, null, null); Assert.assertEquals(2, q.getCount()); int key = q.getColumnIndex(RemoteContract.COLUMN_KEY); int type = q.getColumnIndex(RemoteContract.COLUMN_TYPE); int value = q.getColumnIndex(RemoteContract.COLUMN_VALUE); while (q.moveToNext()) { if (q.getString(key).equals("true")) { Assert.assertEquals(RemoteContract.TYPE_BOOLEAN, q.getInt(type)); Assert.assertEquals(1, q.getInt(value)); } else if (q.getString(key).equals("false")) { Assert.assertEquals(RemoteContract.TYPE_BOOLEAN, q.getInt(type)); Assert.assertEquals(0, q.getInt(value)); } else { Assert.fail(); } } } @Test public void testReadStringSet() { HashSet<String> set = new HashSet<>(); set.add("foo"); set.add("bar;"); set.add("baz"); set.add(""); getSharedPreferences() .edit() .putStringSet("pref", set) .apply(); ContentResolver resolver = getLocalContext().getContentResolver(); Cursor q = resolver.query(getQueryUri("pref"), null, null, null, null); Assert.assertEquals(1, q.getCount()); int key = q.getColumnIndex(RemoteContract.COLUMN_KEY); int type = q.getColumnIndex(RemoteContract.COLUMN_TYPE); int value = q.getColumnIndex(RemoteContract.COLUMN_VALUE); while (q.moveToNext()) { if (q.getString(key).equals("pref")) { Assert.assertEquals(RemoteContract.TYPE_STRING_SET, q.getInt(type)); String serialized = q.getString(value); Assert.assertEquals(set, RemoteUtils.deserializeStringSet(serialized)); } else { Assert.fail(); } } } @Test public void testInsertStringSet() { HashSet<String> set = new HashSet<>(); set.add("foo"); set.add("bar;"); set.add("baz"); set.add(""); ContentValues values = new ContentValues(); values.put(RemoteContract.COLUMN_KEY, "pref"); values.put(RemoteContract.COLUMN_TYPE, RemoteContract.TYPE_STRING_SET); values.put(RemoteContract.COLUMN_VALUE, RemoteUtils.serializeStringSet(set)); ContentResolver resolver = getLocalContext().getContentResolver(); Uri uri = resolver.insert(getQueryUri(null), values); Assert.assertEquals(getQueryUri("pref"), uri); Assert.assertEquals(set, getSharedPreferences().getStringSet("pref", null)); } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
apsun/RemotePreferences
https://github.com/apsun/RemotePreferences/blob/c3e3e59d0b302e2af753f36e54a62c0c6059083b/testapp/src/androidTest/java/com/crossbowffs/remotepreferences/RemoteUtilsTest.java
testapp/src/androidTest/java/com/crossbowffs/remotepreferences/RemoteUtilsTest.java
package com.crossbowffs.remotepreferences; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; @RunWith(AndroidJUnit4.class) public class RemoteUtilsTest { @Test public void testSerializeStringSet() { Set<String> set = new LinkedHashSet<String>(); set.add("foo"); set.add("bar;"); set.add("baz"); set.add(""); String serialized = RemoteUtils.serializeStringSet(set); Assert.assertEquals("foo;bar\\;;baz;;", serialized); } @Test public void testDeserializeStringSet() { Set<String> set = new LinkedHashSet<String>(); set.add("foo"); set.add("bar;"); set.add("baz"); set.add(""); String serialized = RemoteUtils.serializeStringSet(set); Set<String> deserialized = RemoteUtils.deserializeStringSet(serialized); Assert.assertEquals(set, deserialized); } @Test public void testSerializeEmptyStringSet() { Assert.assertEquals("", RemoteUtils.serializeStringSet(new HashSet<String>())); } @Test public void testDeserializeEmptyStringSet() { Assert.assertEquals(new HashSet<String>(), RemoteUtils.deserializeStringSet("")); } @Test public void testDeserializeInvalidStringSet() { try { RemoteUtils.deserializeStringSet("foo;bar"); Assert.fail(); } catch (IllegalArgumentException e) { // Expected } } }
java
MIT
c3e3e59d0b302e2af753f36e54a62c0c6059083b
2026-01-05T02:37:35.218499Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/util/src/main/java/com/tencent/wstt/gt/util/RuntimeHelper.java
util/src/main/java/com/tencent/wstt/gt/util/RuntimeHelper.java
package com.tencent.wstt.gt.util; import android.text.TextUtils; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.List; /** * Helper functions for running processes. */ public class RuntimeHelper { /** * Exec the arguments, using root if necessary. * @param args */ public static Process exec(List<String> args) throws IOException { // since JellyBean, sudo is required to read other apps' logs if (VersionHelper.getVersionSdkIntCompat() >= VersionHelper.VERSION_JELLYBEAN && RootUtil.isRooted()) { Process process = Runtime.getRuntime().exec("su"); PrintStream outputStream = null; try { outputStream = new PrintStream(new BufferedOutputStream(process.getOutputStream(), 8192)); outputStream.println(TextUtils.join(" ", args)); outputStream.flush(); } finally { if (outputStream != null) { outputStream.close(); } } return process; } return Runtime.getRuntime().exec(ArrayUtil.toArray(args, String.class)); } public static void destroy(Process process) { // if we're in JellyBean, then we need to kill the process as root, which requires all this // extra UnixProcess logic if (VersionHelper.getVersionSdkIntCompat() >= VersionHelper.VERSION_JELLYBEAN && RootUtil.isRooted()) { RootUtil.destroy(process); } else { process.destroy(); } } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/util/src/main/java/com/tencent/wstt/gt/util/FileUtil.java
util/src/main/java/com/tencent/wstt/gt/util/FileUtil.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.io.Reader; import java.io.Writer; import java.net.Socket; import java.nio.channels.FileChannel; public class FileUtil { /** * 关闭bufferReader * * @param br */ public static void closeReader(Reader br) { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 关闭Writer * * @param br */ public static void closeWriter(Writer wr) { if (wr != null) { try { wr.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * flush Writer * * @param br */ public static void flushWriter(Writer wr) { if (wr != null) { try { wr.flush(); } catch (IOException e) { e.printStackTrace(); } } } /** * 输入流的关闭 * * @param in */ public static void closeInputStream(InputStream in) { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 输出流的关闭 * * @param out */ public static void closeOutputStream(OutputStream out) { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 文件管道的关闭 * * @param in */ public static void closeFileChannel(FileChannel chl) { if (chl != null) { try { chl.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * RandomAccessFile的关闭 * * @param f RandomAccessFile对象 */ public static void closeRandomAccessFile(RandomAccessFile f) { if (f != null) { try { f.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Socket的关闭 * * @param s Socket对象 */ public static void colseSocket(Socket s) { if (s != null) { try { s.close(); } catch (IOException e) { e.printStackTrace(); } } } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/util/src/main/java/com/tencent/wstt/gt/util/package-info.java
util/src/main/java/com/tencent/wstt/gt/util/package-info.java
/** * @author yoyoqin * GT其他模块依赖的工具包 */ package com.tencent.wstt.gt.util;
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/util/src/main/java/com/tencent/wstt/gt/util/VersionHelper.java
util/src/main/java/com/tencent/wstt/gt/util/VersionHelper.java
package com.tencent.wstt.gt.util; import android.os.Build; import java.lang.reflect.Field; public class VersionHelper { public static final int VERSION_CUPCAKE = 3; public static final int VERSION_DONUT = 4; public static final int VERSION_FROYO = 8; public static final int VERSION_JELLYBEAN = 16; private static Field sdkIntField = null; private static boolean fetchedSdkIntField = false; public static int getVersionSdkIntCompat() { try { Field field = getSdkIntField(); if (field != null) { return (Integer) field.get(null); } } catch (IllegalAccessException ignore) { // ignore } return VERSION_CUPCAKE; // cupcake } private static Field getSdkIntField() { if (!fetchedSdkIntField) { try { sdkIntField = Build.VERSION.class.getField("SDK_INT"); } catch (NoSuchFieldException ignore) { // ignore } fetchedSdkIntField = true; } return sdkIntField; } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/util/src/main/java/com/tencent/wstt/gt/util/RootUtil.java
util/src/main/java/com/tencent/wstt/gt/util/RootUtil.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.util; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RootUtil { private static final Pattern PID_PATTERN = Pattern.compile("\\d+"); private static final Pattern SPACES_PATTERN = Pattern.compile("\\s+"); public static boolean rootJustNow = false; public static boolean isRooted() { BufferedReader reader; boolean flag = false; try { reader = terminal("ls /data/"); if (reader.readLine() != null) { flag = true; } } catch (Exception e) { e.printStackTrace(); } rootJustNow = flag; return flag; } private static BufferedReader terminal(String command) throws Exception { Process process = Runtime.getRuntime().exec("su"); // 执行到这,Superuser会跳出来,选择是否允许获取最高权限 OutputStream outstream = process.getOutputStream(); DataOutputStream DOPS = new DataOutputStream(outstream); InputStream instream = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader( new DataInputStream(instream))); String temp = command + "\n"; // 加回车 DOPS.writeBytes(temp); // 执行 DOPS.flush(); // 刷新,确保都发送到outputstream DOPS.writeBytes("exit\n"); // 退出 DOPS.flush(); process.waitFor(); return br; } public static void destroy(Process process) { // stupid method for getting the pid, but it actually works Matcher matcher = PID_PATTERN.matcher(process.toString()); matcher.find(); int pid = Integer.parseInt(matcher.group()); List<Integer> allRelatedPids = getAllRelatedPids(pid); for (Integer relatedPid : allRelatedPids) { destroyPid(relatedPid); } } private static void destroyPid(int pid) { Process suProcess = null; PrintStream outputStream = null; try { suProcess = Runtime.getRuntime().exec("su"); outputStream = new PrintStream(new BufferedOutputStream( suProcess.getOutputStream(), 8192)); outputStream.println("kill " + pid); outputStream.println("exit"); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) { outputStream.close(); } if (suProcess != null) { try { suProcess.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } } } private static List<Integer> getAllRelatedPids(final int pid) { List<Integer> result = new ArrayList<Integer>(Arrays.asList(pid)); // use 'ps' to get this pid and all pids that are related to it (e.g. // spawned by it) try { final Process suProcess = Runtime.getRuntime().exec("su"); new Thread(new Runnable() { @Override public void run() { PrintStream outputStream = null; try { outputStream = new PrintStream( new BufferedOutputStream( suProcess.getOutputStream(), 8192)); outputStream.println("ps"); outputStream.println("exit"); outputStream.flush(); } finally { if (outputStream != null) { outputStream.close(); } } } }).run(); if (suProcess != null) { try { suProcess.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new InputStreamReader( suProcess.getInputStream()), 8192); while (bufferedReader.ready()) { String[] line = SPACES_PATTERN.split(bufferedReader .readLine()); if (line.length >= 3) { try { if (pid == Integer.parseInt(line[2])) { result.add(Integer.parseInt(line[1])); } } catch (NumberFormatException ignore) { } } } } finally { if (bufferedReader != null) { bufferedReader.close(); } } } catch (IOException e1) { e1.printStackTrace(); } return result; } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/util/src/main/java/com/tencent/wstt/gt/util/ArrayUtil.java
util/src/main/java/com/tencent/wstt/gt/util/ArrayUtil.java
package com.tencent.wstt.gt.util; import java.lang.reflect.Array; import java.util.List; public class ArrayUtil { public static <T> int indexOf(T[] array, T object) { for (int i = 0; i < array.length; i++) { if (object.equals(array[i])) { return i; } } return -1; } // copied from Java 6 source public static int[] copyOfRange(int[] original, int start, int end) { if (start <= end) { if (original.length >= start && 0 <= start) { int length = end - start; int copyLength = Math.min(length, original.length - start); int[] copy = new int[length]; System.arraycopy(original, start, copy, 0, copyLength); return copy; } throw new ArrayIndexOutOfBoundsException(); } throw new IllegalArgumentException(); } public static boolean[] copyOf(boolean[] original, int newLength) { boolean[] copy = new boolean[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } public static int[] copyOf(int[] original, int newLength) { int[] copy = new int[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } @SuppressWarnings("unchecked") public static <T> T[] copyOf(T[] original, int newLength) { return (T[]) copyOf(original, newLength, original.getClass()); } @SuppressWarnings("unchecked") public static <T, U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { T[] copy = ((Object) newType == (Object) Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } public static Object[] concatenate(Object[] first, Object[] second) { Object[] result = new Object[first.length + second.length]; for (int i = 0; i < first.length; i++) { result[i] = first[i]; } for (int i = 0; i < second.length; i++) { result[i + first.length] = second[i]; } return result; } public static int[] concatenate(int[] first, int[] second) { int[] result = new int[first.length + second.length]; for (int i = 0; i < first.length; i++) { result[i] = first[i]; } for (int i = 0; i < second.length; i++) { result[i + first.length] = second[i]; } return result; } public static boolean[] concatenate(boolean[] first, boolean[] second) { boolean[] result = new boolean[first.length + second.length]; for (int i = 0; i < first.length; i++) { result[i] = first[i]; } for (int i = 0; i < second.length; i++) { result[i + first.length] = second[i]; } return result; } public static boolean contains(int[] arr, int value) { for (int i = 0; i < arr.length; i++) { if (arr[i] == value) { return true; } } return false; } public static <T> T[] toArray(List<T> list, Class<T> clazz) { @SuppressWarnings("unchecked") T[] result = (T[]) Array.newInstance(clazz, list.size()); for (int i = 0; i < list.size(); i++) { result[i] = list.get(i); } return result; } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/util/src/main/java/com/tencent/wstt/gt/util/DoubleUtils.java
util/src/main/java/com/tencent/wstt/gt/util/DoubleUtils.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.util; import java.math.BigDecimal; /** * Double数据的操作 使用Java,double 进行运算时,经常出现精度丢失的问题,总是在一个正确的结果左右偏0.0000**1。 * 特别在实际项目中,通过一个公式校验该值是否大于0,如果大于0我们会做一件事情,小于0我们又处理其他事情。 * 这样的情况通过double计算出来的结果去和0比较大小,尤其是有小数点的时候,经常会因为精度丢失而导致程序处理流程出错。 */ public class DoubleUtils { /** * double 乘法 * * @param d1 * @param d2 * @return */ public static double mul(double d1, double d2) { BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); try { return bd1.multiply(bd2).doubleValue(); } catch (Exception e) { // 根据bugly观测,在进入GTOpMulPerfActivity页时有极小概率crash,故加上异常保护 // @see http://bugly.qq.com/detail?app=900010910&pid=1&ii=152#stack e.printStackTrace(); return 0; } } /** * double 除法 * * @param d1 * @param d2 * @param scale * 四舍五入 小数点位数 * @return */ public static double div(double d1, double d2, int scale) { // 当然在此之前,你要判断分母是否为0, // 为0你可以根据实际需求做相应的处理 BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); // return bd1.divide(bd2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); // 直接向下取整,保持和UI展示一致 try { return bd1.divide(bd2, scale, BigDecimal.ROUND_DOWN).doubleValue(); } catch (Exception e) { // 根据bugly观测,在进入GTOpMulPerfActivity页时有极小概率crash,故加上异常保护 // @see http://bugly.qq.com/detail?app=900010910&pid=1&ii=46#stack e.printStackTrace(); return 0; } } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/app/src/main/java/com/tencent/wstt/gt/gttools/MainActivity.java
app/src/main/java/com/tencent/wstt/gt/gttools/MainActivity.java
package com.tencent.wstt.gt.gttools; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/util/ProcessCPUUtils.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/util/ProcessCPUUtils.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * CPU相关工具类。 */ public class ProcessCPUUtils { /** * 获取CPU使用率,注意本方法执行会停留interval的秒数,所以不要在工作线程中调用 * @param pid 指定要采集的进程号 * @param interval 采样间隔 * @return [进程的CPU使用率, 进程的Jiffies数] */ public static double[] getUsage(int pid, int interval) { double[] result = new double[2]; String[] resultP = null; String[] resultA = null; double startPCpu = 0.0; double startAllCpu = 0.0; double endPCpu = 0.0; double endAllCpu = 0.0; if (pid <= 0) return result; resultP = getProcessCpuAction(pid); if (null != resultP) { startPCpu = Double.parseDouble(resultP[1]) + Double.parseDouble(resultP[2]); } resultA = getCpuAction(); if (null != resultA) { for (int i = 2; i < resultA.length; i++) { startAllCpu += Double.parseDouble(resultA[i]); } } // 采样间隔不能太短,否则会造成性能空耗 if (interval < 10) { interval = 1000; } try { Thread.sleep(interval); } catch (InterruptedException e) { e.printStackTrace(); } resultP = getProcessCpuAction(pid); if (null != resultP) { endPCpu = Double.parseDouble(resultP[1]) + Double.parseDouble(resultP[2]); } resultA = getCpuAction(); if (null != resultA) { for (int i = 2; i < resultA.length; i++) { endAllCpu += Double.parseDouble(resultA[i]); } } if ((endAllCpu - startAllCpu) != 0) { result[0] = DoubleUtils.div(((endPCpu - startPCpu) * 100.00), (endAllCpu - startAllCpu), 2); if (result[0] < 0) { result[0] = 0; } else if (result[0] > 100) { result[0] = 100; } } result[1] = startPCpu; return result; } private static String[] getCpuAction() { String cpuPath = "/proc/stat"; String cpu = ""; String[] result = new String[7]; File f = new File(cpuPath); if (!f.exists() || !f.canRead()) { return null; } FileReader fr = null; BufferedReader localBufferedReader = null; try { fr = new FileReader(f); localBufferedReader = new BufferedReader(fr, 8192); cpu = localBufferedReader.readLine(); if (null != cpu) { result = cpu.split(" "); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } FileUtil.closeReader(localBufferedReader); return result; } private static String[] getProcessCpuAction(int pid) { String cpuPath = "/proc/" + pid + "/stat"; String cpu = ""; String[] result = new String[3]; File f = new File(cpuPath); if (!f.exists() || !f.canRead()) { /* * 进程信息可能无法读取, * 同时发现此类进程的PSS信息也是无法获取的,用PS命令会发现此类进程的PPid是1, * 即/init,而其他进程的PPid是zygote, * 说明此类进程是直接new出来的,不是Android系统维护的 */ return null; } FileReader fr = null; BufferedReader localBufferedReader = null; try { fr = new FileReader(f); localBufferedReader = new BufferedReader(fr, 8192); cpu = localBufferedReader.readLine(); if (null != cpu) { String[] cpuSplit = cpu.split(" "); result[0] = cpuSplit[1]; result[1] = cpuSplit[13]; result[2] = cpuSplit[14]; } }catch (IOException e) { e.printStackTrace(); } FileUtil.closeReader(localBufferedReader); return result; } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/util/FileUtil.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/util/FileUtil.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.io.Reader; import java.io.Writer; import java.net.Socket; import java.nio.channels.FileChannel; public class FileUtil { /** * 关闭bufferReader * * @param br */ public static void closeReader(Reader br) { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 关闭Writer * * @param wr */ public static void closeWriter(Writer wr) { if (wr != null) { try { wr.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * flush Writer * * @param wr */ public static void flushWriter(Writer wr) { if (wr != null) { try { wr.flush(); } catch (IOException e) { e.printStackTrace(); } } } /** * 输入流的关闭 * * @param in */ public static void closeInputStream(InputStream in) { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 输出流的关闭 * * @param out */ public static void closeOutputStream(OutputStream out) { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 文件管道的关闭 * * @param chl */ public static void closeFileChannel(FileChannel chl) { if (chl != null) { try { chl.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * RandomAccessFile的关闭 * * @param f RandomAccessFile对象 */ public static void closeRandomAccessFile(RandomAccessFile f) { if (f != null) { try { f.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Socket的关闭 * * @param s Socket对象 */ public static void colseSocket(Socket s) { if (s != null) { try { s.close(); } catch (IOException e) { e.printStackTrace(); } } } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/util/package-info.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/util/package-info.java
/** * @author yoyoqin * 从GT中剥离出的基本性能指标采集实现的工具包 */ package com.tencent.wstt.gt.datasource.util;
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/util/UidNETUtils.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/util/UidNETUtils.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.util; import android.net.TrafficStats; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class UidNETUtils { /** * 流量采集方案,可自定义扩展 * @author yoyoqin */ public static interface Case { long getTxBytes(int uid) throws Exception; long getRxBytes(int uid) throws Exception; boolean test(int uid); } public static class CaseInvalid implements Case { @Override public long getTxBytes(int uid) throws Exception { return 0; } @Override public long getRxBytes(int uid) throws Exception { return 0; } @Override public boolean test(int uid) { return false; } } public static class CaseUidStat implements Case { @Override public long getTxBytes(int uid) throws Exception { String netPath = "/proc/uid_stat/" + uid + "/tcp_snd"; File f = new File(netPath); if (!f.exists()) { throw new Exception(netPath + "not found."); } else { FileReader fr = new FileReader(netPath); BufferedReader localBufferedReader = new BufferedReader(fr, 8192); String ret = localBufferedReader.readLine(); FileUtil.closeReader(localBufferedReader); return Long.parseLong(ret); } } @Override public long getRxBytes(int uid) throws Exception { String netPath = "/proc/uid_stat/" + uid + "/tcp_rcv"; File f = new File(netPath); if (!f.exists()) { throw new Exception(netPath + "not found."); } else { FileReader fr = new FileReader(netPath); BufferedReader localBufferedReader = new BufferedReader(fr, 8192); String ret = localBufferedReader.readLine(); FileUtil.closeReader(localBufferedReader); return Long.parseLong(ret); } } @Override public boolean test(int uid) { int testUid = uid <= 0 ? 1000 : uid; try { getRxBytes(testUid); getTxBytes(testUid); } catch (Exception e) { return false; } return true; } } public static class CaseTrafficStats implements Case { @Override public long getTxBytes(int uid) throws Exception { return TrafficStats.getUidTxBytes(uid); } @Override public long getRxBytes(int uid) throws Exception { return TrafficStats.getUidRxBytes(uid); } @Override public boolean test(int uid) { int testUid = uid <= 0 ? 1000 : uid; try { long n = getRxBytes(testUid) + getTxBytes(testUid); if (n <= 0) { return false; } } catch (Exception e) { return false; } return true; } } //============================================================================== private static Case sampleCase = new CaseUidStat(); public static Case getSampleCase() { return sampleCase; } public static void setSampleCase(Case newCase) { sampleCase = newCase; } private static final double B2K = 1024.00d; /** * 获取上下行流量,单位为KB * @param uid 目标uid号,如果输入0或负数,则默认用uid=1000(system server)来测试 * @return {tx,rx} * @throws Exception */ public static double[] getTxRxKB(int uid) throws Exception { return new double[]{sampleCase.getTxBytes(uid) / B2K, sampleCase.getRxBytes(uid) / B2K}; } /** * 获取上下行流量,单位为Byte * @param uid 目标uid号,如果输入0或负数,则默认用uid=1000(system server)来测试 * @return {tx,rx} * @throws Exception */ public static long[] getTxRxBytes(int uid) throws Exception { return new long[]{sampleCase.getTxBytes(uid), sampleCase.getRxBytes(uid)}; } /** * 测试本方案是否可用 * @param uid 测试uid号,如果输入0或负数,则默认用uid=1000(system server)来测试 * @return true可用,false不可用 */ public static boolean test(int uid) { return sampleCase.test(uid); } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/util/SMUtils.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/util/SMUtils.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.util; import android.os.Handler; import android.os.Looper; import android.view.Choreographer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * 获取本进程的流畅度信息 */ public class SMUtils { private static boolean running; private static AtomicInteger i = new AtomicInteger(0); private static Choreographer.FrameCallback c = new Choreographer.FrameCallback() { @Override public void doFrame(long frameTimeNanos) { if (!running) { return; } // 本工具类中只负责帧数的递增计数,需要在调用端控制计数器的清零时机 i.incrementAndGet(); Choreographer.getInstance().postFrameCallback(this); } }; /** * 启动流畅度的采集 * @return 核心计数器 */ public static AtomicInteger startSampleSM() { Handler h = new Handler(Looper.getMainLooper()); h.post(new Runnable() { @Override public void run() { running = true; Choreographer.getInstance().postFrameCallback(c); } }); return i; } public static void stopSampleSM() { running = false; i.set(0); } public static boolean isRunning() { return running; } /** * 基于标准流畅度为60的算分方法 * @param lst 计算数据源 * @return 计算结果列表 */ public static int[] getSmDetail(List<Long> lst) { int[] resultList = new int[6]; if (lst == null || lst.size() == 0) return resultList; double delta = 1.2; double w = 0.4; int s = 5; int count5 = 0; long minsm = 60; int ktimes = 0; int high = 0; int highScore = 0; int lowScore = 0; int low = 0; int total = 0; int count = 0; double resultn = 0; double result = 0; long lastdata = -1; double sscore = 0; double kscore = 0; ArrayList<Long> tempDataList = new ArrayList<Long>(); long sm = 0; for (int i = 0; i < lst.size(); i++) { count5 += 1; try { sm = lst.get(i); } catch (Exception e) { } minsm = (minsm > sm) ? sm : minsm; if (sm < 40) { ktimes += 1; } if (count5 == s) { if (minsm >= 40) { high += 1; } else { low += 1; minsm *= Math.pow(delta, 1.0 / ktimes - 1); } total += 1; tempDataList.add(minsm); minsm = 60; count5 = 0; ktimes = 0; } } if (count5 > 0) { if (minsm >= 40) high += 1; else { low += 1; minsm *= Math.pow(delta, 1.0 / ktimes - 1); } total += 1; tempDataList.add(minsm); } resultList[0] = low / total; count = 0; resultn = 0; result = 0; lastdata = -1; sscore = 0; kscore = 0; for (int i = 0; i < tempDataList.size(); i++) { Long data = tempDataList.get(i); if (lastdata < 0) { lastdata = data; } if (data >= 40) { if (lastdata < 40) { kscore += resultn; result += resultn; count = 0; resultn = 0; } resultn += getScore(data); count += 1; } else { if (lastdata >= 40) { result += resultn * w; sscore += resultn; count = 0; resultn = 0; } count += 1; resultn += getScore(data); } lastdata = data; } if (count > 0 && lastdata < 40) { result += resultn; kscore += resultn; } if (count > 0 && lastdata >= 40) { result += resultn * w; sscore += resultn; } if (low > 0) { lowScore = (int) (kscore * 100 / low); } if (high > 0) { highScore = (int) (sscore * 100 / high); } resultList[1]= low * 5; resultList[2] = lowScore; resultList[3] = high * 5; resultList[4] = highScore; resultList[5] = (int) (result * 100 / (high * w + low)); return resultList; } private static double getScore(Long data) { if (data < 20) { return data * 1.5 / 100.0; } else if (data < 30 && data >= 20) { return 0.3 + (data - 20) * 3 / 100.0; } else if (data < 50 && data >= 30) { return 0.6 + (data - 30) / 100.0; } else { return 0.8 + (data - 50) * 2 / 100.0; } } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/util/CPUUtils.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/util/CPUUtils.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.util; import java.io.IOException; import java.io.RandomAccessFile; /** * CPU相关工具类。 */ public class CPUUtils { /** * 获取CPU使用率,注意本方法执行会停留interval的毫秒数,所以不要在工作线程中调用 * @param interval 采样间隔 * @return 手机整机的CPU使用率 */ public static double getUsage(int interval) { double usage = 0.0; double start_cpu = 0.0; double start_idle = 0.0; double end_cpu = 0.0; double end_idle = 0.0; RandomAccessFile reader = null; try { reader = new RandomAccessFile("/proc/stat", "r"); String load = reader.readLine(); String[] toks = load.split(" "); start_idle = Double.parseDouble(toks[5]); start_cpu = Double.parseDouble(toks[2]) + Double.parseDouble(toks[3]) + Double.parseDouble(toks[4]) + Double.parseDouble(toks[6]) + Double.parseDouble(toks[8]) + Double.parseDouble(toks[7]); } catch (IOException e) { e.printStackTrace(); } finally { FileUtil.closeRandomAccessFile(reader); } // 采样间隔不能太短,否则会造成性能空耗 if (interval < 10) { interval = 1000; } try { Thread.sleep(interval); } catch (InterruptedException e) { e.printStackTrace(); } try { reader = new RandomAccessFile("/proc/stat", "r"); String load = reader.readLine(); String[] toks = load.split(" "); end_idle = Double.parseDouble(toks[5]); end_cpu = Double.parseDouble(toks[2]) + Double.parseDouble(toks[3]) + Double.parseDouble(toks[4]) + Double.parseDouble(toks[6]) + Double.parseDouble(toks[8]) + Double.parseDouble(toks[7]); } catch (IOException e) { e.printStackTrace(); } finally { FileUtil.closeRandomAccessFile(reader); } if (0 != ((start_idle + start_cpu) - (end_idle + end_cpu))) { usage = DoubleUtils.div((100.00 * ((end_cpu - start_cpu))), ((end_cpu + end_idle) - (start_cpu + start_idle)), 2); // 修正4.x之前的系统bug数据 if (usage < 0) { usage = 0; } else if (usage > 100) { usage = 100; } } return usage; } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/util/MEMUtils.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/util/MEMUtils.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.util; import android.app.ActivityManager; import android.content.Context; import android.os.Debug; import android.os.Debug.MemoryInfo; import java.lang.reflect.Method; /** * 内存信息工具类。 */ public class MEMUtils { /** * 获取内存信息:total、free、buffers、cached,单位MB * * @return 内存信息{total,free,buffers,cached} */ public static long[] getMemInfo() { long memInfo[] = new long[4]; try { Class<?> procClazz = Class.forName("android.os.Process"); Class<?> paramTypes[] = new Class[] { String.class, String[].class, long[].class }; Method readProclines = procClazz.getMethod("readProcLines", paramTypes); Object args[] = new Object[3]; final String[] memInfoFields = new String[] { "MemTotal:", "MemFree:", "Buffers:", "Cached:" }; long[] memInfoSizes = new long[memInfoFields.length]; memInfoSizes[0] = 30; memInfoSizes[1] = -30; args[0] = new String("/proc/meminfo"); args[1] = memInfoFields; args[2] = memInfoSizes; if (null != readProclines) { readProclines.invoke(null, args); for (int i = 0; i < memInfoSizes.length; i++) { memInfo[i] = memInfoSizes[i] / 1024; } } } catch (Exception e) { e.printStackTrace(); } return memInfo; } /** * 获取进程内存Private Dirty数据 * * @param context Android上下文 * @param pid 进程ID * @return {nativePrivateDirty,dalvikPrivateDirty,TotalPrivateDirty} */ public static long[] getPrivDirty(Context context, int pid) { ActivityManager mAm = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); int[] pids = new int[1]; pids[0] = pid; MemoryInfo[] memoryInfoArray = mAm.getProcessMemoryInfo(pids); MemoryInfo pidMemoryInfo = memoryInfoArray[0]; long[] value = new long[3]; // Natvie Dalvik Total value[0] = pidMemoryInfo.nativePrivateDirty; value[1] = pidMemoryInfo.dalvikPrivateDirty; value[2] = pidMemoryInfo.getTotalPrivateDirty(); return value; } /** * 获取进程内存PSS数据 * * @param context Android上下文 * @param pid 进程ID * @return {nativePss,dalvikPss,TotalPss} */ public static long[] getPSS(Context context, int pid) { long[] value = new long[3]; // Natvie Dalvik Total if (pid >= 0) { int[] pids = new int[1]; pids[0] = pid; ActivityManager mAm = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); MemoryInfo[] memoryInfoArray = mAm.getProcessMemoryInfo(pids); MemoryInfo pidMemoryInfo = memoryInfoArray[0]; value[0] = pidMemoryInfo.nativePss; value[1] = pidMemoryInfo.dalvikPss; value[2] = pidMemoryInfo.getTotalPss(); } else { value[0] = 0; value[1] = 0; value[2] = 0; } return value; } /** * 获取本进程的内存Heap数据 * 注:该数值与Java方式虚拟机算法的内存值一致,和Dumpsys meminfo方式的数值有较大出入 * @return {NativeSize,NativeAllocatedSize,DalvikSize,DalvikAllocatedSize,HeapSize,HeapAllocatedSize} */ public static long[] getHeap() { long[] value = new long[6]; // NativeSize,NativeAllocatedSize,DalvikSize,DalvikAllocatedSize,HeapSize,HeapAllocatedSize long[] nativeValue = getHeapNative(); long[] dalvikValue = getHeapDalvik(); value[0] = nativeValue[0]; value[1] = nativeValue[1]; value[2] = dalvikValue[0]; value[3] = dalvikValue[1]; value[4] = nativeValue[0] + dalvikValue[0]; value[5] = nativeValue[1] + dalvikValue[1]; return value; } public static long[] getHeapNative() { long[] value = new long[2]; value[0] = Debug.getNativeHeapSize() >> 10; value[1] = Debug.getNativeHeapAllocatedSize() >> 10; return value; } public static long[] getHeapDalvik() { long[] value = new long[2]; value[0] = Runtime.getRuntime().totalMemory() >> 10; // Runtime取的就是虚拟机算法的内存值 value[1] = (Runtime.getRuntime().totalMemory() - Runtime .getRuntime().freeMemory()) >> 10; return value; } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/util/NETUtils.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/util/NETUtils.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.util; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.TrafficStats; import android.telephony.TelephonyManager; public class NETUtils { private static final int TYPE_WIFI = 0; private static final int TYPE_FAST = 1; private static final int TYPE_GPRS = 2; private static final double B2K = 1024.00d; /** * 获取网络连接类型 * * @return -1表示没有网络 */ public static final int getNetWorkType(Context c) { ConnectivityManager conn = (ConnectivityManager) c .getSystemService(Context.CONNECTIVITY_SERVICE); if (conn == null) { return -1; } NetworkInfo info = conn.getActiveNetworkInfo(); if (info == null || !info.isAvailable()) { return -1; } int type = info.getType(); if (type == ConnectivityManager.TYPE_WIFI) { return TYPE_WIFI; } else { TelephonyManager tm = (TelephonyManager) c .getSystemService(Context.TELEPHONY_SERVICE); switch (tm.getNetworkType()) { case TelephonyManager.NETWORK_TYPE_CDMA: return TYPE_GPRS; case TelephonyManager.NETWORK_TYPE_EDGE: return TYPE_GPRS; case TelephonyManager.NETWORK_TYPE_GPRS: return TYPE_GPRS; default: return TYPE_FAST; } } } /** * 获取整体的网络接收流量,包括wifi和Mobile * * @return 总字节数 */ public static long getNetRxTotalBytes() { long total = TrafficStats.getTotalRxBytes(); return total; } /** * 获取整体的网络输出流量,包括wifi和Mobile * * @return 总字节数 */ public static long getNetTxTotalBytes() { long total = TrafficStats.getTotalTxBytes(); return total; } public static long getNetTxMobileBytes() { long total = TrafficStats.getMobileTxBytes(); return total; } public static long getNetRxMobileBytes() { long total = TrafficStats.getMobileRxBytes(); return total; } public static long getNetTxWifiBytes() { long total = getNetTxTotalBytes() - getNetTxMobileBytes(); return total; } public static long getNetRxWifiBytes() { long total = getNetRxTotalBytes() - getNetRxMobileBytes(); return total; } /** * 获取整体的网络接收流量,包括wifi和Mobile * * @return 总数据包数 */ public static long getNetRxTotalPackets() { long total = TrafficStats.getTotalRxPackets(); return total; } /** * 获取整体的网络输出流量,包括wifi和Mobile * * @return 总数据包数 */ public static long getNetTxTotalPackets() { long total = TrafficStats.getTotalRxPackets(); return total; } private static long t_base_wifi = 0; private static long t_base_3G = 0; private static long t_base_2G = 0; private static long r_base_wifi = 0; private static long r_base_3G = 0; private static long r_base_2G = 0; private static double t_add_wifi = 0; private static double t_add_3G = 0; private static double t_add_2G = 0; private static double r_add_wifi = 0; private static double r_add_3G = 0; private static double r_add_2G = 0; public static double getT_add_wifi() { return t_add_wifi; } public static double getT_add_3G() { return t_add_3G; } public static double getT_add_2G() { return t_add_2G; } public static double getR_add_wifi() { return r_add_wifi; } public static double getR_add_3G() { return r_add_3G; } public static double getR_add_2G() { return r_add_2G; } /** * 归零 */ public static void initNetValue() { t_base_wifi = getNetTxWifiBytes(); t_base_3G = t_base_2G = getNetTxMobileBytes(); r_base_wifi = getNetRxWifiBytes(); r_base_3G = r_base_2G = getNetRxMobileBytes(); t_add_wifi = 0; t_add_3G = 0; t_add_2G = 0; r_add_wifi = 0; r_add_3G = 0; r_add_2G = 0; } private static long t_cur_wifi = 0; private static long t_cur_3G = 0; private static long t_cur_2G = 0; private static long r_cur_wifi = 0; private static long r_cur_3G = 0; private static long r_cur_2G = 0; /** * 获取当前流量值 * @param c * @return {t_add_wifi, r_add_wifi, t_add_3G, r_add_3G, t_add_2G, r_add_2G} */ public static double[] getNetTxRxKB(Context c) { double[] result = new double[6]; int cur_net_type = getNetWorkType(c); switch (cur_net_type) { case TYPE_WIFI: t_cur_wifi = getNetTxWifiBytes(); r_cur_wifi = getNetRxWifiBytes(); t_add_wifi = (t_cur_wifi - t_base_wifi) / B2K; r_add_wifi = (r_cur_wifi - r_base_wifi) / B2K; break; case TYPE_FAST: t_cur_3G = getNetTxMobileBytes(); r_cur_3G = getNetRxMobileBytes(); t_add_3G = (t_cur_3G - t_base_3G) / B2K; r_add_3G = (r_cur_3G - r_base_3G) / B2K; break; case TYPE_GPRS: t_cur_2G = getNetTxMobileBytes(); r_cur_2G = getNetRxMobileBytes(); t_add_2G = (t_cur_2G - t_base_2G) / B2K; r_add_2G = (r_cur_2G - r_base_2G) / B2K; break; } result[0] = t_add_wifi; result[1] = r_add_wifi; result[2] = t_add_3G; result[3] = r_add_3G; result[4] = t_add_2G; result[5] = r_add_2G; return result; } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/util/DoubleUtils.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/util/DoubleUtils.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.util; import java.math.BigDecimal; /** * Double数据的操作 使用Java,double 进行运算时,经常出现精度丢失的问题,总是在一个正确的结果左右偏0.0000**1。 * 特别在实际项目中,通过一个公式校验该值是否大于0,如果大于0我们会做一件事情,小于0我们又处理其他事情。 * 这样的情况通过double计算出来的结果去和0比较大小,尤其是有小数点的时候,经常会因为精度丢失而导致程序处理流程出错。 */ public class DoubleUtils { /** * double 乘法 * * @param d1 * @param d2 * @return 乘积结果 */ public static double mul(double d1, double d2) { BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); try { return bd1.multiply(bd2).doubleValue(); } catch (Exception e) { // 根据bugly观测,在进入GTOpMulPerfActivity页时有极小概率crash,故加上异常保护 // @see http://bugly.qq.com/detail?app=900010910&pid=1&ii=152#stack e.printStackTrace(); return 0; } } /** * double 除法 * * @param d1 * @param d2 * @param scale * 四舍五入 小数点位数 * @return 除法结果 */ public static double div(double d1, double d2, int scale) { // 当然在此之前,你要判断分母是否为0, // 为0你可以根据实际需求做相应的处理 BigDecimal bd1 = new BigDecimal(Double.toString(d1)); BigDecimal bd2 = new BigDecimal(Double.toString(d2)); // return bd1.divide(bd2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); // 直接向下取整,保持和UI展示一致 try { return bd1.divide(bd2, scale, BigDecimal.ROUND_DOWN).doubleValue(); } catch (Exception e) { // 根据bugly观测,在进入GTOpMulPerfActivity页时有极小概率crash,故加上异常保护 // @see http://bugly.qq.com/detail?app=900010910&pid=1&ii=46#stack e.printStackTrace(); return 0; } } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/util/FrameUtils.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/util/FrameUtils.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.util; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; public class FrameUtils { private static Process process; private static DataOutputStream os; private static BufferedReader ir; /** * 获取总的帧数,这是计算帧率的数据源 * @return 从service call SurfaceFlinger 1013命令中得到的累积帧数 * @throws IOException */ public static synchronized int getFrameNum() throws IOException { String frameNumString = ""; String getFps40 = "service call SurfaceFlinger 1013"; if (process == null) { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); ir = new BufferedReader( new InputStreamReader(process.getInputStream())); } os.writeBytes(getFps40 + "\n"); os.flush(); String str = ""; int index1 = 0; int index2 = 0; while ((str = ir.readLine()) != null) { if (str.indexOf("(") != -1) { index1 = str.indexOf("("); index2 = str.indexOf(" "); frameNumString = str.substring(index1 + 1, index2); break; } } int frameNum; if (!frameNumString.equals("")) { frameNum = Integer.parseInt(frameNumString, 16); } else { frameNum = 0; } return frameNum; } public static synchronized void destory() { try { os.writeBytes("exit\n"); os.flush(); os.close(); ir.close(); } catch (IOException e) { } process.destroy(); process = null; } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/NETTimerTask.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/NETTimerTask.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.engine; import android.content.Context; import com.tencent.wstt.gt.datasource.util.NETUtils; import java.util.TimerTask; /** * 整机流量采集引擎 */ public class NETTimerTask extends TimerTask { Context c; private DataRefreshListener<Double[]> dataRefreshListener; /** * 构造方法 * @param c Android上下文 * @param dataRefreshListener 数据的监听器 */ public NETTimerTask(Context c, DataRefreshListener<Double[]> dataRefreshListener) { this.c = c; this.dataRefreshListener = dataRefreshListener; } public void run() { double result[] = NETUtils.getNetTxRxKB(c); Double temp[] = new Double[result.length]; for (int i = 0; i < result.length; i++) { temp[i] = Double.valueOf(result[i]); } dataRefreshListener.onRefresh(System.currentTimeMillis(), temp); } public void stop() { this.cancel(); } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/HeapTimerTask.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/HeapTimerTask.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.engine; import com.tencent.wstt.gt.datasource.util.MEMUtils; import java.util.TimerTask; /** * 本进程Heap维度内存采集引擎 */ public class HeapTimerTask extends TimerTask { private DataRefreshListener<Long[]> dataRefreshListener; /** * 构造方法 * @param dataRefreshListener 数据的监听器 */ public HeapTimerTask(DataRefreshListener<Long[]> dataRefreshListener) { this.dataRefreshListener = dataRefreshListener; } public void run() { long result[] = MEMUtils.getHeap(); Long temp[] = new Long[result.length]; for (int i = 0; i < result.length; i++) { temp[i] = Long.valueOf(result[i]); } dataRefreshListener.onRefresh(System.currentTimeMillis(), temp); } public void stop() { this.cancel(); } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/MEMTimerTask.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/MEMTimerTask.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.engine; import com.tencent.wstt.gt.datasource.util.MEMUtils; import java.util.TimerTask; /** * 整机内存采集引擎 */ public class MEMTimerTask extends TimerTask { private DataRefreshListener<Long[]> dataRefreshListener; /** * 构造方法 * @param dataRefreshListener 数据的监听器 */ public MEMTimerTask(DataRefreshListener<Long[]> dataRefreshListener) { this.dataRefreshListener = dataRefreshListener; } public void run() { long result[] = MEMUtils.getMemInfo(); dataRefreshListener.onRefresh(System.currentTimeMillis(), new Long[]{Long.valueOf((int)result[0]), Long.valueOf((int)result[1]), Long.valueOf((int)result[2]), Long.valueOf((int)result[3])}); } public void stop() { this.cancel(); } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/FPSTimerTask.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/FPSTimerTask.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.engine; import com.tencent.wstt.gt.datasource.util.FrameUtils; import java.io.IOException; import java.util.TimerTask; /** * Andorid4.0以上版本,使用此FPS获取的实现,要比原有方案简单稳定 */ public class FPSTimerTask extends TimerTask { private long startTime = 0L; private int lastFrameNum = 0; private long testCount = 0; private boolean hasSu = true; private DataRefreshListener<Long> dataRefreshListener; /** * 构造方法 * @param dataRefreshListener FPS数据监听者 * @param hasSu 可以指定是否root,事实上想要采集FPS数据是必须root */ public FPSTimerTask(DataRefreshListener<Long> dataRefreshListener, boolean hasSu) { this.dataRefreshListener = dataRefreshListener; this.hasSu = hasSu; } public boolean isHasSu() { return hasSu; } public void setHasSu(boolean hasSu) { this.hasSu = hasSu; } /* * 主循环,和2.3方案不同的是,本主循环1s执行一次,2.3方案是0.5s执行一次 * @see java.util.TimerTask#run() */ public void run() { /* * Timer的启动无法避免,所以这里加root保护 * 若未root,直接返回,减少空消耗 */ if (! hasSu) { return; } long end = 0L; float realCostTime = 0.0F; end = System.nanoTime(); if (testCount != 0) { realCostTime = (float) (end - startTime) / 1000000.0F; } startTime = System.nanoTime(); if (testCount == 0) { try { lastFrameNum = FrameUtils.getFrameNum(); } catch (IOException e) { e.printStackTrace(); } } int currentFrameNum = 0; try { currentFrameNum = FrameUtils.getFrameNum(); } catch (IOException e) { e.printStackTrace(); } int FPS = currentFrameNum - lastFrameNum; if (realCostTime > 0.0F) { int fpsResult = (int) (FPS * 1000 / realCostTime); // 根据值变化的监听 dataRefreshListener.onRefresh(System.currentTimeMillis(), Long.valueOf(fpsResult)); } lastFrameNum = currentFrameNum; testCount += 1; } public synchronized void stop() { FrameUtils.destory(); } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/package-info.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/package-info.java
/** * @author yoyoqin * 性能数据采集引擎,供给使用AndroidJUnit的自动化脚本直接使用或进一步封装 */ package com.tencent.wstt.gt.datasource.engine;
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/CPUTimerTask.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/CPUTimerTask.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.engine; import com.tencent.wstt.gt.datasource.util.CPUUtils; import com.tencent.wstt.gt.datasource.util.ProcessCPUUtils; import java.util.TimerTask; /** * CPU数据采集引擎,以定时任务的方式实现,因为CPU采集算法中会停滞指定的时间,所以该任务在定时器的时间间隔要设置为1ms。 * 支持整机CPU的采集和指定进程CPU的采集。 */ public class CPUTimerTask extends TimerTask implements TargetChangeable<Integer>{ private int pid; private int interval; private DataRefreshListener<Double> cpuFreshListener; private DataRefreshListener<Long> jiffiesFreshListener; /** * 构造方法 * @param pid 指定进程号,0或负数为采集整机的CPU数据 * @param interval 采样间隔 * @param cpuFreshListener CPU数据的回调 * @param jiffiesFreshListener CPU时间片数据回调,只在采集指定进程的数据时有效 */ public CPUTimerTask(int pid, int interval, DataRefreshListener<Double> cpuFreshListener, DataRefreshListener<Long> jiffiesFreshListener) { this.pid = pid; this.interval = interval; this.cpuFreshListener = cpuFreshListener; this.jiffiesFreshListener = jiffiesFreshListener; } public void run() { if (pid > 0) // 进程的 { double result[] = ProcessCPUUtils.getUsage(pid, interval); cpuFreshListener.onRefresh(System.currentTimeMillis(), Double.valueOf(result[0]), this); jiffiesFreshListener.onRefresh(System.currentTimeMillis(), Long.valueOf((long)result[1]), this); } else // 整机的 { double result = CPUUtils.getUsage(interval); cpuFreshListener.onRefresh(System.currentTimeMillis(), Double.valueOf(result)); } } public void stop() { this.cancel(); } @Override public Integer getTarget() { return pid; } @Override public void setTarget(Integer pid) { this.pid = pid; } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/SMTimerTask.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/SMTimerTask.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.engine; import com.tencent.wstt.gt.datasource.util.SMUtils; import java.lang.reflect.Field; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicInteger; /** * 流畅度数据采集引擎,用于采集本进程的流畅度数据 */ public class SMTimerTask extends TimerTask { private boolean isGetPeriod = false; // 是否已获取执行间隔值 private long thisPeriod = 1000; // 默认1000ms,在初次执行时要通过反射方法在超类中获取真实值 private DataRefreshListener<Long> dataRefreshListener; private AtomicInteger count; /** * 构造方法 * @param dataRefreshListener 数据的监听器 */ public SMTimerTask(DataRefreshListener<Long> dataRefreshListener) { this.dataRefreshListener = dataRefreshListener; count = SMUtils.startSampleSM(); } /* * 主循环,1s执行一次 * @see java.util.TimerTask#run() */ public void run() { if (!SMUtils.isRunning()) { return; } // Task的执行采样间隔 if (! isGetPeriod) { Class<?> clz = TimerTask.class; Field superPeriod; try { superPeriod = clz.getDeclaredField("period"); superPeriod.setAccessible(true); thisPeriod = superPeriod.getLong(this); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } isGetPeriod = true; } int x = count.getAndSet(0); // 需要根据采样间隔对刷新次数进行放大或缩小 dataRefreshListener.onRefresh(System.currentTimeMillis(), Long.valueOf(x * 1000 / thisPeriod)); } public void stop() { this.cancel(); SMUtils.stopSampleSM(); } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/PrivateDirtyTimerTask.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/PrivateDirtyTimerTask.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.engine; import android.content.Context; import com.tencent.wstt.gt.datasource.util.MEMUtils; import java.util.TimerTask; /** * 进程的PrivateDirty维度内存采集引擎 */ public class PrivateDirtyTimerTask extends TimerTask implements TargetChangeable<Integer>{ private Context c; private int pid; private DataRefreshListener<Long[]> dataRefreshListener; /** * 构造方法 * @param c Android上下文 * @param pid 指定进程号 * @param dataRefreshListener 数据的监听器 */ public PrivateDirtyTimerTask(Context c, int pid, DataRefreshListener<Long[]> dataRefreshListener) { this.c = c; this.pid = pid; this.dataRefreshListener = dataRefreshListener; } public void run() { long result[] = MEMUtils.getPrivDirty(c, pid); Long temp[] = new Long[result.length]; for (int i = 0; i < result.length; i++) { temp[i] = Long.valueOf(result[i]); } dataRefreshListener.onRefresh(System.currentTimeMillis(), temp, this); } public void stop() { this.cancel(); } @Override public Integer getTarget() { return pid; } @Override public void setTarget(Integer pid) { this.pid = pid; } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/TargetChangeable.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/TargetChangeable.java
package com.tencent.wstt.gt.datasource.engine; /** *采集目标可变的接口。 * 比如pid,在测试过程中被测目标的进程号经常有改变的情况,如果想延续原来的采集任务,可以中途改变它。 */ public interface TargetChangeable<T> { T getTarget(); void setTarget(T t); }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/DataRefreshListener.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/DataRefreshListener.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.engine; public abstract class DataRefreshListener<T> implements IDataRefreshListener<T>{ /** * 为了支持接口TargetChangeable且老的用户不需要修改代码, * 将DataRefreshListener从interface降级为抽象类,提供onRefresh3个参数默认实现, * 保持原有对DataRefreshListener使用不变 */ @Override public void onRefresh(long time, T data, TargetChangeable target){} /** * 也提供onRefresh方法2个参数的空实现,这样需要使用3个参数的新用户,就不需要额外写2个参数的实现了 */ @Override public void onRefresh(long time, T data){} }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/UidNETTimerTask.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/UidNETTimerTask.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.engine; import com.tencent.wstt.gt.datasource.util.UidNETUtils; import java.util.TimerTask; /** * 指定UID的流量数据采集引擎 */ public class UidNETTimerTask extends TimerTask { private int uid; private DataRefreshListener<Double[]> dataRefreshListener; /** * 构造方法 * @param uid 指定UID * @param dataRefreshListener 数据的监听器 */ public UidNETTimerTask(int uid, DataRefreshListener<Double[]> dataRefreshListener) { this.uid = uid; this.dataRefreshListener = dataRefreshListener; } public void run() { double result[] = {}; try { result = UidNETUtils.getTxRxKB(uid); } catch (Exception e) { e.printStackTrace(); } Double temp[] = new Double[result.length]; for (int i = 0; i < result.length; i++) { temp[i] = Double.valueOf(result[i]); } dataRefreshListener.onRefresh(System.currentTimeMillis(), temp); } public void stop() { this.cancel(); } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/PssTimerTask.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/PssTimerTask.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.engine; import android.content.Context; import com.tencent.wstt.gt.datasource.util.MEMUtils; import java.util.TimerTask; /** * 进程的PSS维度内存采集引擎 */ public class PssTimerTask extends TimerTask implements TargetChangeable<Integer>{ private Context c; private int pid; private DataRefreshListener<Long[]> dataRefreshListener; /** * 构造方法 * @param c Android上下文 * @param pid 指定进程号 * @param dataRefreshListener 数据的监听器 */ public PssTimerTask(Context c, int pid, DataRefreshListener<Long[]> dataRefreshListener) { this.c = c; this.pid = pid; this.dataRefreshListener = dataRefreshListener; } public void run() { long result[] = MEMUtils.getPSS(c, pid); Long temp[] = new Long[result.length]; for (int i = 0; i < result.length; i++) { temp[i] = Long.valueOf(result[i]); } dataRefreshListener.onRefresh(System.currentTimeMillis(), temp, this); } public void stop() { this.cancel(); } @Override public Integer getTarget() { return pid; } @Override public void setTarget(Integer pid) { this.pid = pid; } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/IDataRefreshListener.java
datasource/src/main/java/com/tencent/wstt/gt/datasource/engine/IDataRefreshListener.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource.engine; public interface IDataRefreshListener<T> { void onRefresh(long time, T data); void onRefresh(long time, T data, TargetChangeable target); }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/AllTest.java
datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/AllTest.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource; import android.support.test.InstrumentationRegistry; import com.tencent.wstt.gt.datasource.engine.CPUTimerTask; import com.tencent.wstt.gt.datasource.engine.DataRefreshListener; import com.tencent.wstt.gt.datasource.engine.FPSTimerTask; import com.tencent.wstt.gt.datasource.engine.HeapTimerTask; import com.tencent.wstt.gt.datasource.engine.MEMTimerTask; import com.tencent.wstt.gt.datasource.engine.NETTimerTask; import com.tencent.wstt.gt.datasource.engine.PrivateDirtyTimerTask; import com.tencent.wstt.gt.datasource.engine.PssTimerTask; import com.tencent.wstt.gt.datasource.engine.SMTimerTask; import com.tencent.wstt.gt.datasource.engine.UidNETTimerTask; import com.tencent.wstt.gt.datasource.util.UidNETUtils; import org.junit.Test; import java.util.Timer; public class AllTest { @Test public void tesAll() throws InterruptedException { Timer timer = new Timer(); Timer timerFPS = new Timer(); Timer timerSM = new Timer(); Timer timerCPU = new Timer(); // FPS FPSTimerTask taskFPS = new FPSTimerTask(new DataRefreshListener<Long>() { @Override public void onRefresh(long time, Long data) { System.out.println("FPS:" + data); } }, true); timerFPS.schedule(taskFPS, 0, 1000); // SM SMTimerTask taskSM = new SMTimerTask(new DataRefreshListener<Long>() { @Override public void onRefresh(long time, Long data) { System.out.println("SM:" + data); } }); timerSM.schedule(taskSM, 1000, 1000); // Other CPUTimerTask task2 = new CPUTimerTask(android.os.Process.myPid(), 1000, new DataRefreshListener<Double>() { @Override public void onRefresh(long time, Double data) { System.out.println("Process CPU:" + data); } }, new DataRefreshListener<Long>() { @Override public void onRefresh(long time, Long data) { System.out.println("Process Jiffies:" + data); } }); timerCPU.schedule(task2, 0, 1); MEMTimerTask task4 = new MEMTimerTask( new DataRefreshListener<Long[]>() { @Override public void onRefresh(long time, Long[] data) { System.out.println("MEM:" + data[0] + "/" + data[1] + "/" + data[2] + "/" + data[3]); } }); timer.schedule(task4, 0, 1000); PssTimerTask task5 = new PssTimerTask(InstrumentationRegistry.getTargetContext(), android.os.Process.myPid(), new DataRefreshListener<Long[]>() { @Override public void onRefresh(long time, Long[] data) { System.out.println("PSS:" + data[0] + "/" + data[1] + "/" + data[2]); } }); timer.schedule(task5, 0, 1000); PrivateDirtyTimerTask task6 = new PrivateDirtyTimerTask(InstrumentationRegistry.getTargetContext(), android.os.Process.myPid(), new DataRefreshListener<Long[]>() { @Override public void onRefresh(long time, Long[] data) { System.out.println("Private Dirty:" + data[0] + "/" + data[1] + "/" + data[2]); } }); timer.schedule(task6, 0, 1000); NETTimerTask task7 = new NETTimerTask(InstrumentationRegistry.getTargetContext(), new DataRefreshListener<Double[]>() { @Override public void onRefresh(long time, Double[] data) { System.out.println("NET:" + data[0] + "/" + data[1] + "/" + data[2] + "/" + data[3] + "/" + data[4] + "/" + data[5]); } }); timer.schedule(task7, 0, 1000); HeapTimerTask task8 = new HeapTimerTask( new DataRefreshListener<Long[]>(){ @Override public void onRefresh(long time, Long[] data) { System.out.println(data[0] + "/" + data[1] + "/" + data[2] + "/" + data[3] + "/" + data[4] + "/" + data[5]); }}); timer.schedule(task8, 0, 1000); // 需要先选择适合自己环境的采集方案 if (!UidNETUtils.test(-1)) { UidNETUtils.Case c = new UidNETUtils.CaseTrafficStats(); if (!c.test(-1)) c = new UidNETUtils.CaseInvalid(); UidNETUtils.setSampleCase(c); } UidNETTimerTask task9 = new UidNETTimerTask(1000, new DataRefreshListener<Double[]>() { @Override public void onRefresh(long time, Double[] data) { System.out.println("UID NET:" + data[0] + "/" + data[1]); } }); timer.schedule(task9, 0, 1000); Thread.sleep(20000); } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/SMTest.java
datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/SMTest.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource; import com.tencent.wstt.gt.datasource.engine.DataRefreshListener; import com.tencent.wstt.gt.datasource.engine.SMTimerTask; import com.tencent.wstt.gt.datasource.util.SMUtils; import junit.framework.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Timer; public class SMTest { @Test public void testSMBase() throws InterruptedException { Timer timer = new Timer(); SMTimerTask taskSM = new SMTimerTask(new DataRefreshListener<Long>() { @Override public void onRefresh(long time, Long data) { System.out.println("SM:" + data); } }); timer.schedule(taskSM, 1000, 1000); // 初始执行的时候也要延迟1000,因为立即采集的数据是0 Thread.sleep(10000); } @Test public void testSMStop() throws InterruptedException { Timer timer = new Timer(); SMTimerTask taskSM = new SMTimerTask(new DataRefreshListener<Long>() { @Override public void onRefresh(long time, Long data) { System.out.println("SM:" + data); } }); timer.schedule(taskSM, 1000, 1000); Thread.sleep(5000); taskSM.stop(); Thread.sleep(5000); } @Test public void testGetSMDetail() throws InterruptedException { // 准备一组假数据 List<Long> lst = new ArrayList<Long>(); for (int i = 0; i < 100; i++) { lst.add(Long.valueOf(60)); } lst.add(Long.valueOf(10)); for (int i = 0; i < 100; i++) { lst.add(Long.valueOf(60)); } int[] result = SMUtils.getSmDetail(lst); Assert.assertTrue(result[5] < 95); Assert.assertEquals(result[1], 5); } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false
r551/GTTools
https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/NETTest.java
datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/NETTest.java
/* * Tencent is pleased to support the open source community by making * Tencent GT (Version 2.4 and subsequent versions) available. * * Notwithstanding anything to the contrary herein, any previous version * of Tencent GT shall not be subject to the license hereunder. * All right, title, and interest, including all intellectual property rights, * in and to the previous version of Tencent GT (including any and all copies thereof) * shall be owned and retained by Tencent and subject to the license under the * Tencent GT End User License Agreement (http://gt.qq.com/wp-content/EULA_EN.html). * * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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 com.tencent.wstt.gt.datasource; import android.support.test.InstrumentationRegistry; import com.tencent.wstt.gt.datasource.engine.DataRefreshListener; import com.tencent.wstt.gt.datasource.engine.NETTimerTask; import com.tencent.wstt.gt.datasource.engine.UidNETTimerTask; import com.tencent.wstt.gt.datasource.util.UidNETUtils; import org.junit.Test; import java.util.Timer; public class NETTest { @Test // 需要权限:android.permission.ACCESS_NETWORK_STATE public void testNet() throws InterruptedException { Timer timer = new Timer(); NETTimerTask task = new NETTimerTask(InstrumentationRegistry.getTargetContext(), new DataRefreshListener<Double[]>(){ @Override public void onRefresh(long time, Double[] data) { System.out.println(data[0] + "/" + data[1] + "/" + data[2]+ "/" + data[3]+ "/" + data[4]+ "/" + data[5]); }}); timer.schedule(task, 0, 1000); Thread.sleep(10000); } @Test public void testUidNet() throws InterruptedException { Timer timer = new Timer(); // 需要先选择适合自己环境的采集方案 if (!UidNETUtils.test(-1)) { UidNETUtils.Case c = new UidNETUtils.CaseTrafficStats(); if (!c.test(-1)) c = new UidNETUtils.CaseInvalid(); UidNETUtils.setSampleCase(c); } UidNETTimerTask task = new UidNETTimerTask(1000, new DataRefreshListener<Double[]>(){ @Override public void onRefresh(long time, Double[] data) { System.out.println(data[0] + "/" + data[1]); }}); timer.schedule(task, 0, 1000); Thread.sleep(100000); } }
java
MIT
e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5
2026-01-05T02:37:34.026955Z
false