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 |
|---|---|---|---|---|---|---|---|---|
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/package-info.java | datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/package-info.java | /**
* @author yoyoqin
*
*/
package com.tencent.wstt.gt.datasource; | 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/ApplicationTest.java | datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/ApplicationTest.java | package com.tencent.wstt.gt.datasource;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | 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/MEMTest.java | datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/MEMTest.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.HeapTimerTask;
import com.tencent.wstt.gt.datasource.engine.MEMTimerTask;
import com.tencent.wstt.gt.datasource.engine.PrivateDirtyTimerTask;
import com.tencent.wstt.gt.datasource.engine.PssTimerTask;
import org.junit.Test;
import java.util.Timer;
public class MEMTest {
@Test
public void testMem() throws InterruptedException
{
Timer timer = new Timer();
MEMTimerTask task = new MEMTimerTask(
new DataRefreshListener<Long[]>(){
@Override
public void onRefresh(long time, Long[] data) {
System.out.println(data[0] + "/" + data[1] + "/" + data[2]+ "/" + data[3]);
}});
timer.schedule(task, 0, 1000);
Thread.sleep(10000);
}
@Test
public void testPss() throws InterruptedException
{
Timer timer = new Timer();
PssTimerTask task = new PssTimerTask(InstrumentationRegistry.getTargetContext(), android.os.Process.myPid(),
new DataRefreshListener<Long[]>(){
@Override
public void onRefresh(long time, Long[] data) {
System.out.println(data[0] + "/" + data[1] + "/" + data[2]);
}});
timer.schedule(task, 0, 1000);
Thread.sleep(10000);
}
@Test
public void testPrivateDirty() throws InterruptedException
{
Timer timer = new Timer();
PrivateDirtyTimerTask task = new PrivateDirtyTimerTask(InstrumentationRegistry.getTargetContext(), android.os.Process.myPid(),
new DataRefreshListener<Long[]>(){
@Override
public void onRefresh(long time, Long[] data) {
System.out.println(data[0] + "/" + data[1] + "/" + data[2]);
}});
timer.schedule(task, 0, 1000);
Thread.sleep(10000);
}
@Test
public void testHeap() throws InterruptedException
{
Timer timer = new Timer();
HeapTimerTask task = 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(task, 0, 1000);
Thread.sleep(10000);
}
}
| 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/UseOutParamTest.java | datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/UseOutParamTest.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.runner.AndroidJUnit4;
import com.tencent.wstt.gt.datasource.engine.CPUTimerTask;
import com.tencent.wstt.gt.datasource.engine.DataRefreshListener;
import com.tencent.wstt.gt.datasource.engine.MEMTimerTask;
import com.tencent.wstt.gt.monitor.model.AbsOutParam;
import com.tencent.wstt.gt.monitor.model.TimeBean;
import com.tencent.wstt.gt.monitor.simple.DoubleOutParam;
import com.tencent.wstt.gt.monitor.simple.DoubleThresholdListener;
import com.tencent.wstt.gt.monitor.simple.LongOutParam;
import com.tencent.wstt.gt.monitor.simple.LongThresholdListener;
import com.tencent.wstt.gt.monitor.threshold.IGTComparator;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Timer;
/**
* Created by yoyoqin on 2016/5/31.
*/
@RunWith(AndroidJUnit4.class)
public class UseOutParamTest {
/**
* 利用出参的阈值能力对超过10%的CPU进行告警
*/
@Test
public void testCPUWithOutParamThreshold() throws InterruptedException
{
// 创建用于监控CPU指标的对象
final DoubleOutParam cpuOutParam = new DoubleOutParam(null, "CPU");
cpuOutParam.setRecord(true); // 启动记录
cpuOutParam.setMonitor(true); // 启动告警监控
/*
* 设置CPU超出10的告警阈值
*/
cpuOutParam.addThresholdListener(new DoubleThresholdListener<AbsOutParam<Double>>(10.0d, 1, null, 0, null, 0) {
@Override
public void onHigherThan(AbsOutParam<Double> src, Double data, IGTComparator<Double> c) {
// 当CPU超过10时,触发该回调,输出下面的信息到控制台
System.out.println("CPU higher than "+ c.getTarget() + ":" + data);
}
@Override
public void onLowerThan(AbsOutParam<Double> src, Double data, IGTComparator<Double> c) {
}
@Override
public void onEquals(AbsOutParam<Double> src, Double data, IGTComparator<Double> c) {
}
});
/*
* 初始化CPU数据采集任务,监听中使用前面创建的cpuOutParam对象对CPU数据进行监控
* 进程号填0,关注的即整机的CPU
*/
CPUTimerTask task = new CPUTimerTask(0, 1000,
new DataRefreshListener<Double>(){
@Override
public void onRefresh(long time, Double data) {
cpuOutParam.setValue(time, Double.valueOf(data));
System.out.println("CPU:" + data);
}},null);
// 启动定时任务,注意因为任务本身有1000ms的时间间隔,所以定时任务的间隔填最小的1ms
// CPU指标的采集之所以如此设计,是为了和其他指标采集方式保持一致
Timer timer = new Timer();
timer.schedule(task, 0, 1);
Thread.sleep(10000);
// 打印此时已记录的CPU历史数据
for (TimeBean<Double> timeBean : cpuOutParam.getRecordList())
{
System.out.println("CPU:" + timeBean.data + " Time:" + timeBean.time);
}
}
/**
* 利用出参的阈值能力对手机内存低于800MB时进行告警
*/
@Test
public void testMEMWithOutParamThreshold() throws InterruptedException
{
final LongOutParam memOutParam = new LongOutParam(null, "MEM");
final LongOutParam memAllOutParam = new LongOutParam(null, "Total");
final LongOutParam memFreeOutParam = new LongOutParam(null, "Free");
memFreeOutParam.setRecord(true); // 启动记录
memFreeOutParam.setMonitor(true); // 启动告警监控
// 设置Free内存低于800M的告警阈值
memFreeOutParam.addThresholdListener(new LongThresholdListener<AbsOutParam<Long>>(null, 0, 800L, 1, null, 0) {
@Override
public void onHigherThan(AbsOutParam<Long> src, Long data, IGTComparator<Long> c) {
}
@Override
public void onLowerThan(AbsOutParam<Long> src, Long data, IGTComparator<Long> c) {
// 当Free内存低于800MB时会触发此告警向控制台输出打印信息
System.out.println("MEM Free lower than "+ c.getTarget() + ", " + c.getCount() + " times:" + data);
}
@Override
public void onEquals(AbsOutParam<Long> src, Long data, IGTComparator<Long> c) {
}
});
memOutParam.addChild(memAllOutParam);
memOutParam.addChild(memFreeOutParam);
// 对手机整机的内存数据进行监控
MEMTimerTask task = new MEMTimerTask(new DataRefreshListener<Long[]>(){
@Override
public void onRefresh(long time, Long[] data) {
memOutParam.getChild(0).setValue(time, data[0]);
memOutParam.getChild(1).setValue(time, data[1] + data[2] + data[3]);
System.out.println("MEM Free/Total:" + (data[1] + data[2] + data[3]) + "/" + data[0]);
}});
// 启动定时任务,因为内存数据是即时值,所以定时1000ms采集一次
Timer timer = new Timer();
timer.schedule(task, 0, 1000);
Thread.sleep(10000);
// 打印此时已记录的剩余内存历史数据
for (TimeBean<Long> timeBean : memOutParam.getChild(1).getRecordList())
{
System.out.println("MEM Free:" + timeBean.data + " Time:" + timeBean.time);
}
}
}
| 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/CPUTest.java | datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/CPUTest.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.CPUTimerTask;
import com.tencent.wstt.gt.datasource.engine.DataRefreshListener;
import org.junit.Test;
import java.util.Timer;
public class CPUTest {
@Test
public void testCPU() throws InterruptedException
{
Timer timer = new Timer();
// 进程号填0,关注的即整机的CPU
CPUTimerTask task = new CPUTimerTask(0, 1000,
new DataRefreshListener<Double>(){
@Override
public void onRefresh(long time, Double data) {
System.out.println("CPU:" + data);
}},null);
timer.schedule(task, 0, 1);
Thread.sleep(10000);
}
@Test
public void testProcessCPU() throws InterruptedException
{
Timer timer = new Timer();
// 测试代码中以自身进程数据
CPUTimerTask task = new CPUTimerTask(android.os.Process.myPid(), 1000,
new DataRefreshListener<Double>(){
@Override
public void onRefresh(long time, Double data) {
System.out.println("CPU:" + data);
}},
new DataRefreshListener<Long>(){
@Override
public void onRefresh(long time, Long data) {
System.out.println("Jiffies:" + data);
}});
timer.schedule(task, 0, 1);
Thread.sleep(10000);
}
}
| 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/FPSTest.java | datasource/src/androidTest/java/com/tencent/wstt/gt/datasource/FPSTest.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.FPSTimerTask;
import org.junit.Test;
import java.util.Timer;
public class FPSTest {
@Test
public void testFpsBase() throws InterruptedException
{
Timer timer = new Timer();
FPSTimerTask task = new FPSTimerTask(new DataRefreshListener<Long>(){
@Override
public void onRefresh(long time, Long data) {
System.out.println(data);
}}, true);
timer.schedule(task, 0, 1000);
Thread.sleep(10000);
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/test/java/com/tencent/wstt/gt/monitor/BaseTest.java | monitor/src/test/java/com/tencent/wstt/gt/monitor/BaseTest.java | package com.tencent.wstt.gt.monitor;
import com.tencent.wstt.gt.monitor.model.AbsOutParam;
import com.tencent.wstt.gt.monitor.model.Group;
import com.tencent.wstt.gt.monitor.model.Key;
import com.tencent.wstt.gt.monitor.simple.LongOutParam;
import com.tencent.wstt.gt.monitor.simple.LongThresholdListener;
import com.tencent.wstt.gt.monitor.threshold.IGTComparator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class BaseTest {
Queue<Long> queue;
@Before
public void setUp()
{
// 准备测试用数据源
queue = new LinkedList<>();
for (long i = 0; i < 20; i++)
{
queue.add(i);
}
}
@Test
public void testSingleParam()
{
// 数据监控对象
LongOutParam singleParam = new LongOutParam(null, "singleParam");
singleParam.setRecord(true);
singleParam.setMonitor(true);
// 三个用于辅助测试结果检验的数据容器
final List<Long> higherThanList = mock(ArrayList.class);
final List<Long> lowerThanList = mock(ArrayList.class);
final List<Long> equalsList = mock(ArrayList.class);
/*
* 分别设置对关注数据源大于、小于、等于的告警阈值分别为大于10、小于9,等于5
*/
singleParam.addThresholdListener(new LongThresholdListener<AbsOutParam<Long>>(10L, 1, 9L, 1, 5L, 1){
@Override
public void onHigherThan(AbsOutParam<Long> src, Long data, IGTComparator<Long> c) {
higherThanList.add(data);
}
@Override
public void onLowerThan(AbsOutParam<Long> src, Long data, IGTComparator<Long> c) {
lowerThanList.add(data);
}
@Override
public void onEquals(AbsOutParam<Long> src, Long data, IGTComparator<Long> c) {
equalsList.add(data);
}});
// 依次遍历数据源中的数据
for (Long value : queue)
{
singleParam.setValue(value);
}
// 校验点,触发大于10的数据告警9次(11~19),小于9的数据告警9次(0~8),等于5的数据告警1次
verify(higherThanList, times(9)).add(anyLong());
verify(lowerThanList, times(9)).add(anyLong());
verify(equalsList, times(1)).add(anyLong());
}
@Test
public void testGroupParam()
{
Group<Key> group = new Group<Key>("test");
LongOutParam singleParam = new LongOutParam(group, "singleParam");
singleParam.setRecord(true);
Assert.assertEquals(group.isEmpty(), false);
group.clear();
Assert.assertEquals(group.isEmpty(), true);
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/model/TimeBean.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/model/TimeBean.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.monitor.model;
/**
* Created by yoyoqin on 2016/5/31.
*/
public class TimeBean<T extends Comparable> implements Comparable<T> {
public final long time;
public final T data;
public TimeBean(long time, T data)
{
this.time = time;
this.data = data;
}
@Override
public int compareTo(T another) {
return data.compareTo(another);
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/model/AbsOutParam.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/model/AbsOutParam.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.monitor.model;
import com.tencent.wstt.gt.monitor.threshold.IThresholdListener;
import com.tencent.wstt.gt.monitor.threshold.ThresholdEntry;
import java.util.ArrayList;
import java.util.List;
abstract public class AbsOutParam<T extends Comparable> implements Key {
protected String key;
protected String alias;
protected T value;
protected T freezeValue;
// 是否记录历史数据
private boolean record;
// 是否已进行告警监听
private boolean monitor;
// Group代表生命周期
private Group<Key> group;
public AbsOutParam(Group<Key> group, String key)
{
this.group = group;
if (null != group)
{
group.register(this);
}
this.key = key;
}
private List<AbsOutParam<T>> children;
private DataRecorder<TimeBean<T>> recorder;
private ThresholdEntry<AbsOutParam<T>, T> thresholdEntry;
public Group<Key> getGroup() {
return group;
}
public void setGroup(Group<Key> group)
{
this.group = group;
}
public String getKey() {
return this.key;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public T getFreezeValue() {
return freezeValue;
}
public void setFreezeValue(T freezeValue) {
this.freezeValue = freezeValue;
}
public boolean isRecord() {
return record;
}
public void setRecord(boolean record) {
this.record = record;
}
public boolean isMonitor() {
return monitor;
}
public void setMonitor(boolean monitor) {
this.monitor = monitor;
}
public T getValue() {
return value;
}
public void setValue(T value) {
if (null == value) {
return;
} else {
this.value = value;
this.freezeValue = value;
}
if (record && checkValue(value))
{
record(System.currentTimeMillis(), value);
}
if (monitor)
{
threshold(value);
}
}
public void setValue(long time, T value) {
if (null == value) {
return;
} else {
this.value = value;
this.freezeValue = value;
}
if (record && checkValue(value))
{
record(time, value);
}
if (monitor)
{
threshold(value);
}
}
public synchronized void addChild(AbsOutParam<T> child)
{
if (null == children)
{
children = new ArrayList<AbsOutParam<T>>(3); // 通常子参数不会超过3个
}
children.add(child);
}
public synchronized AbsOutParam<T> getChild(int i)
{
if (null == children || i >= children.size())
{
return null;
}
return children.get(i);
}
private synchronized void record(long time, T value)
{
if (null == recorder)
{
recorder = new DataRecorder<TimeBean<T>>();
}
TimeBean<T> timeBean = new TimeBean<T>(time, value);
recorder.add(timeBean);
}
private synchronized void threshold(T value)
{
if (monitor && null != thresholdEntry)
{
thresholdEntry.add(value);
}
}
public TimeBean<T> getRecord(int seq)
{
if (null == recorder)
{
return null;
}
return recorder.getRecord(seq);
}
public ArrayList<TimeBean<T>> getRecordList()
{
if (null == recorder)
{
return null;
}
return recorder.getRecordList();
}
public int getRecordSize()
{
if (null == recorder)
{
return 0;
}
return recorder.size();
}
public void clearAllRecords() {
if (children != null && !children.isEmpty())
{
for (AbsOutParam<T> p : children)
{
p.clearAllRecords();
}
}
if (null == recorder)
{
return;
}
recorder.clear();
}
/**
* 增加告警阈值监听
* @param listener 发生告警的监听
*/
public synchronized void addThresholdListener(
IThresholdListener<AbsOutParam<T>, T> listener)
{
if (null == thresholdEntry)
{
thresholdEntry = new ThresholdEntry<AbsOutParam<T>, T>();
}
thresholdEntry.addListener(listener);
}
/**
* 移除告警阈值监听
* @param listener 欲移除的告警阈值监听
*/
public synchronized void removeThresholdListener(
IThresholdListener<AbsOutParam<T>, T> listener)
{
if (null == thresholdEntry) return;
thresholdEntry.removeListener(listener);
}
/**
* 判断输入的值是否有效,只有有效的值才会进行记录和阈值判断
* @param value 输入值
* @return 是否为有效值
*/
abstract public boolean checkValue(T value);
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/model/package-info.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/model/package-info.java | /**
* @author yoyoqin
* 监控模型模块,沿用GT中的参数概念
*/
package com.tencent.wstt.gt.monitor.model; | java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/model/OutParam.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/model/OutParam.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.monitor.model;
/**
* 默认的出参类型,不对值的有效性进行检查
* @author yoyoqin
*
* @param <T> 值类型,GT中默认使用Long
*/
public class OutParam<T extends Comparable> extends AbsOutParam<T> {
public OutParam(Group<Key> group, String key) {
super(group, key);
}
@Override
public boolean checkValue(T value) {
return true;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/model/DataRecorder.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/model/DataRecorder.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.monitor.model;
import java.util.ArrayList;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 保存历史记录的数据结构,GT版本为性能优化剥离出的新设计
* TODO 为应对数据的持久化,这里应该考虑对记录的CURD进行健壮性处理与接口设计
* @since 2.1
*/
public class DataRecorder<T> {
private int size = 0; // 数据源的总长度
private ArrayList<ArrayList<T>> dataSet; // 数据源中分桶
private ArrayList<T> curBucket; // 当前桶,避免总从dataSet计算获取影响效率
// 锁
private ReadWriteLock lock = new ReentrantReadWriteLock();
// 单个存储列表的长度,主要为性能考虑,需要是2的n次方,且方便位移计算
private static final int CAPACITY = 4096;
public DataRecorder()
{
dataSet = new ArrayList<ArrayList<T>>();
}
/**
* @param start 起始数据序号
* @param end 结束数据序号+1,和subList的使用方式保持一致
* @return 数据记录列表
*/
public ArrayList<T> getRecordList(int start, int end) {
if (end <= start)
{
return new ArrayList<T>(0);
}
ArrayList<T> result = new ArrayList<T>(end - start);
int startBucketSeq = start / CAPACITY; // start所在桶的序号
int startLocal = start % CAPACITY; // start在桶中的位置
int endBucketSeq = (end - 1) / CAPACITY; // end所在桶的序号
int endLocal = (end - 1) % CAPACITY; // end在桶中的位置
if (startBucketSeq == endBucketSeq)
{
ArrayList<T> bucket = dataSet.get(startBucketSeq);
lock.readLock().lock();
result.addAll(bucket.subList(startLocal, endLocal + 1));
lock.readLock().unlock();
}
else
{
// 加第一桶
ArrayList<T> startBucket = dataSet.get(startBucketSeq);
lock.readLock().lock();
result.addAll(startBucket.subList(startLocal, startBucket.size() - 1));
lock.readLock().unlock();
// 加中间的桶
for (int i = startBucketSeq + 1; i < endBucketSeq; i++)
{
result.addAll(dataSet.get(i));
}
// 加最后的桶
ArrayList<T> endBucket = dataSet.get(endBucketSeq);
lock.readLock().lock();
result.addAll(endBucket.subList(0, endLocal + 1));
lock.readLock().unlock();
}
return result;
}
public ArrayList<T> getRecordList() {
ArrayList<T> result = new ArrayList<T>();
for (ArrayList<T> list : dataSet)
{
lock.readLock().lock();
result.addAll(list);
lock.readLock().unlock();
}
return result;
}
public T getRecord(int seq) {
if (seq > size)
{
return null;
}
int bucketSeq = seq / CAPACITY; // 所在桶的序号
int local = seq % CAPACITY; // 在桶中的位置
return dataSet.get(bucketSeq).get(local);
}
public void add(T entry) {
lock.writeLock().lock();
int local = size % CAPACITY; // 新加的entry如在桶中位置应该在的位置
if (local == 0)
{
// 新桶第一个记录
curBucket = new ArrayList<T>();
curBucket.add(entry);
dataSet.add(curBucket);
}
else
{
// 可以在当前桶中存放
curBucket.add(entry);
}
size++;
lock.writeLock().unlock();
}
// FIXME 加锁可能更安全一些
public int size() {
return size;
}
public void clear() {
lock.writeLock().lock();
for (ArrayList<T> list : dataSet)
{
list.clear();
}
dataSet.clear();
curBucket = null;
size = 0;
lock.writeLock().unlock();
}
} | java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/model/Group.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/model/Group.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.monitor.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Group<T extends Key> {
// TODO Map应该有更省资源的抽象
protected Map<String, T> outParaMap =
Collections.synchronizedMap(new LinkedHashMap<String, T>());
protected String key;
public Group(String key)
{
this.key = key;
}
public String getKey() {
return key;
}
public void register(T param)
{
outParaMap.put(param.getKey(), param);
}
public void unregister(T param)
{
outParaMap.remove(param.getKey());
}
public boolean isEmpty()
{
return outParaMap.isEmpty();
}
public void clear()
{
outParaMap.clear();
}
public T getParam(String paraKey) {
return outParaMap.get(paraKey);
}
public List<T> getAllParams()
{
List<T> result = new ArrayList<T>();
result.addAll(outParaMap.values());
return result;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/model/Key.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/model/Key.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.monitor.model;
public interface Key {
String getKey();
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/IGTComparator.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/IGTComparator.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.monitor.threshold;
public interface IGTComparator<T> {
boolean checkTrigger(T data);
int getCount();
T getTarget();
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/package-info.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/package-info.java |
/**
* @author yoyoqin
* 从Android GT中重构剥离出的阈值抽象,不依赖于其它包,以充分的可复用性为设计目标
*/
package com.tencent.wstt.gt.monitor.threshold; | java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/IThresholdListener.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/IThresholdListener.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.monitor.threshold;
public interface IThresholdListener<M,T> {
void waring(M src, T data, IGTComparator<T> c);
void addGTComparator(IGTComparator<T> c);
void removeGTComparator(IGTComparator<T> c);
void checkValue(T data);
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/ThresholdAdaptor.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/ThresholdAdaptor.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.monitor.threshold;
import java.util.ArrayList;
import java.util.List;
public abstract class ThresholdAdaptor<M, T extends Comparable<T>> implements IThresholdListener<M,T> {
private List<IGTComparator<T>> comparators;
private M src;
/**
* 扩展用初始方法,后面需要客户代码自己配置比较器
*/
public ThresholdAdaptor()
{
}
/**
* 需要按该构造函数初始化简化的Listener实现类
* @param higherThan
* @param higherD
* @param lowerThan
* @param lowerD
* @param equals
* @param equalsD
*/
public ThresholdAdaptor(
T higherThan, int higherD,
T lowerThan, int lowerD,
T equals, int equalsD)
{
if (null != higherThan) addGTComparator(new GTComparatorHigherThan<T>(higherThan, higherD<=0 ? 1 : higherD));
if (null != lowerThan) addGTComparator(new GTComparatorLowerThan<T>(lowerThan, lowerD<=0 ? 1 : lowerD));
if (null != equals) addGTComparator(new GTComparatorEquals<T>(equals, equalsD<=0 ? 1 : equalsD));
}
@Override
public synchronized void checkValue(T value)
{
for (IGTComparator<T> c : comparators)
{
if (c.checkTrigger(value))
{
waring(src, value, c);
}
}
}
@Override
public synchronized void addGTComparator(IGTComparator<T> c)
{
if (null == comparators)
{
comparators = new ArrayList<IGTComparator<T>>();
}
comparators.add(c);
}
@Override
public synchronized void removeGTComparator(IGTComparator<T> c)
{
if (null == comparators) return;
comparators.remove(c);
}
@Override
public abstract void waring(M src, T data, IGTComparator<T> c);
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/ThresholdEntry.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/ThresholdEntry.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.monitor.threshold;
import java.util.ArrayList;
import java.util.List;
public class ThresholdEntry<M, T> implements IThresholdEntry<M, T> {
private List<IThresholdListener<M, T>> listeners;
private boolean enable;
public ThresholdEntry()
{
}
public void add(T value)
{
if (null == listeners) return;
for (IThresholdListener<M, T> listener : listeners)
{
listener.checkValue(value);
}
}
/**
* 增加告警阈值
* @param listener 发生告警的监听
* @param comparators 告警比较器,默认有大于、小于、等于这3个比较器,支持自定义扩展
*/
@Override
public synchronized void addListener(
IThresholdListener<M, T> listener, GTComparator<T>...comparators)
{
if (null != comparators)
{
for (GTComparator<T> c : comparators)
{
listener.addGTComparator(c);
}
}
if (null == listeners)
{
listeners = new ArrayList<IThresholdListener<M, T>>();
}
listeners.add(listener);
}
/**
* 增加告警阈值,相比前面方法,加上这个重载方法是为了提高性能
* @param listener 发生告警的监听
*/
public synchronized void addListener(IThresholdListener<M, T> listener)
{
if (null == listeners)
{
listeners = new ArrayList<IThresholdListener<M, T>>();
}
listeners.add(listener);
}
/**
* 移除告警阈值监听
* @param listener 欲移除的告警阈值监听
*/
@Override
public synchronized void removeListener(IThresholdListener<M,T> listener) {
if (null != listeners)
{
listeners.remove(listener);
}
}
@Override
public void setEnable(boolean flag) {
this.enable = flag;
}
@Override
public boolean isEnable() {
return enable;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/GTComparatorEquals.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/GTComparatorEquals.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.monitor.threshold;
public class GTComparatorEquals<T extends Comparable<T>> extends GTComparator<T> {
public GTComparatorEquals(T equals, int duration)
{
super(equals, duration);
}
@Override
public boolean checkTrigger(T data) {
if (data.compareTo(target) == 0)
{
count++;
// 注意连续超过持续次数的阈值,会不断触发告警
if (count >= duration)
{
return true;
}
}
else
{
count = 0;
}
return false;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/GTComparatorHigherThan.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/GTComparatorHigherThan.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.monitor.threshold;
public class GTComparatorHigherThan<T extends Comparable<T>> extends GTComparator<T> {
public GTComparatorHigherThan(T highThan, int duration)
{
super(highThan, duration);
}
@Override
public boolean checkTrigger(T data) {
if (data.compareTo(target) > 0)
{
count++;
// 注意连续超过持续次数的阈值,会不断触发告警
if (count >= duration)
{
return true;
}
}
else
{
count = 0;
}
return false;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/GTComparator.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/GTComparator.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.monitor.threshold;
public abstract class GTComparator<T> implements IGTComparator<T> {
T target;
int duration = 1;
int count; // 连续达到过阈值的次数
public GTComparator(T target, int duration)
{
this.target = target;
this.duration = duration;
}
@Override
public abstract boolean checkTrigger(T data);
@Override
public int getCount() {
return count;
}
@Override
public T getTarget()
{
return target;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/SimpleThresholdListener.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/SimpleThresholdListener.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.monitor.threshold;
public abstract class SimpleThresholdListener<M, T extends Comparable<T>> extends ThresholdAdaptor<M, T> {
public SimpleThresholdListener(
T higherThan, int higherD,
T lowerThan, int lowerD,
T equals, int equalsD)
{
super(higherThan, higherD, lowerThan, lowerD, equals, equalsD);
}
@Override
public void waring(M src, T data, IGTComparator<T> c) {
if (c instanceof GTComparatorHigherThan)
{
onHigherThan(src, data, c);
}
else if (c instanceof GTComparatorLowerThan)
{
onLowerThan(src, data, c);
}
else if (c instanceof GTComparatorEquals)
{
onEquals(src, data, c);
}
}
public abstract void onHigherThan(M src, T data, IGTComparator<T> c);
public abstract void onLowerThan(M src, T data, IGTComparator<T> c);
public abstract void onEquals(M src, T data, IGTComparator<T> c);
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/IThresholdEntry.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/IThresholdEntry.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.monitor.threshold;
public interface IThresholdEntry<M, T> {
void addListener(IThresholdListener<M, T> listener, GTComparator<T>... comparators);
void removeListener(IThresholdListener<M, T> listener);
void setEnable(boolean flag);
boolean isEnable();
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/GTComparatorLowerThan.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/threshold/GTComparatorLowerThan.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.monitor.threshold;
public class GTComparatorLowerThan<T extends Comparable<T>> extends GTComparator<T> {
public GTComparatorLowerThan(T lowerThan, int duration)
{
super(lowerThan, duration);
}
@Override
public boolean checkTrigger(T data) {
if (data.compareTo(target) < 0)
{
count++;
// 注意连续超过持续次数的阈值,会不断触发告警
if (count >= duration)
{
return true;
}
}
else
{
count = 0;
}
return false;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/DoubleThresholdListener.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/DoubleThresholdListener.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.monitor.simple;
import com.tencent.wstt.gt.monitor.threshold.IGTComparator;
import com.tencent.wstt.gt.monitor.threshold.SimpleThresholdListener;
/**
* Created by yoyoqin on 2016/5/31.
*/
public abstract class DoubleThresholdListener<M> extends SimpleThresholdListener<M, Double> {
public DoubleThresholdListener(
Double higherThan, int higherD,
Double lowerThan, int lowerD,
Double equals, int equalsD) {
super(higherThan, higherD, lowerThan, lowerD, equals, equalsD);
}
@Override
public void onHigherThan(M src, Double data, IGTComparator<Double> c) {
// 按需要覆写
}
@Override
public void onLowerThan(M src, Double data, IGTComparator<Double> c) {
// 按需要覆写
}
@Override
public void onEquals(M src, Double data, IGTComparator<Double> c) {
// 按需要覆写
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/GroupManager.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/GroupManager.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.monitor.simple;
import com.tencent.wstt.gt.monitor.model.Group;
import com.tencent.wstt.gt.monitor.model.Key;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* 使用Group的调用入口
*/
public class GroupManager {
public static GroupManager INSTANCE = new GroupManager();
// Group的字典容器,以group名称为key的字典
private Map<String, Group<Key>> container = new HashMap<String, Group<Key>>();
private GroupManager()
{
}
public static GroupManager getInstance()
{
return INSTANCE;
}
public Group<Key> getGroup(String key)
{
return container.get(key);
}
synchronized public void addGroup(String key, Group<Key> group)
{
if (! container.containsKey(key))
{
container.put(key, group);
}
}
synchronized public void removeGroup(String key)
{
Group<Key> group = container.remove(key);
group.clear();
}
synchronized public Collection<Group<Key>> getAllGroup()
{
return container.values();
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/package-info.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/package-info.java | /**
* @author yoyoqin
* 监控模型默认的一个简单实现,可以满足常规的监控需求
*/
package com.tencent.wstt.gt.monitor.simple; | java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/DoubleOutParam.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/DoubleOutParam.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.monitor.simple;
import com.tencent.wstt.gt.monitor.model.Group;
import com.tencent.wstt.gt.monitor.model.Key;
import com.tencent.wstt.gt.monitor.model.OutParam;
/**
* Created by yoyoqin on 2016/5/31.
*/
public class DoubleOutParam extends OutParam<Double> {
public DoubleOutParam(Group<Key> group, String key) {
super(group, key);
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/LongOutParam.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/LongOutParam.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.monitor.simple;
import com.tencent.wstt.gt.monitor.model.Group;
import com.tencent.wstt.gt.monitor.model.Key;
import com.tencent.wstt.gt.monitor.model.OutParam;
/**
* @author yoyoqin
*
*/
public class LongOutParam extends OutParam<Long> {
public LongOutParam(Group<Key> group, String key) {
super(group, key);
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/LongThresholdListener.java | monitor/src/main/java/com/tencent/wstt/gt/monitor/simple/LongThresholdListener.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.monitor.simple;
import com.tencent.wstt.gt.monitor.threshold.IGTComparator;
import com.tencent.wstt.gt.monitor.threshold.SimpleThresholdListener;
/**
* @author yoyoqin
*
*/
public abstract class LongThresholdListener<M> extends SimpleThresholdListener<M, Long> {
public LongThresholdListener(
Long higherThan, int higherD,
Long lowerThan, int lowerD,
Long equals, int equalsD) {
super(higherThan, higherD, lowerThan, lowerD, equals, equalsD);
}
@Override
public void onHigherThan(M src, Long data, IGTComparator<Long> c) {
// 按需要覆写
}
@Override
public void onLowerThan(M src, Long data, IGTComparator<Long> c) {
// 按需要覆写
}
@Override
public void onEquals(M src, Long data, IGTComparator<Long> c) {
// 按需要覆写
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/facade/src/test/java/com/tencent/wstt/gt/facade/ExampleUnitTest.java | facade/src/test/java/com/tencent/wstt/gt/facade/ExampleUnitTest.java | package com.tencent.wstt.gt.facade;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/facade/src/main/java/com/tencent/wstt/gt/facade/EvnSet.java | facade/src/main/java/com/tencent/wstt/gt/facade/EvnSet.java | package com.tencent.wstt.gt.facade;
import android.content.Context;
/**
* 环境信息,目前的作用是:
* 如果是Android环境,需要传入上下文Context
* 这样在具体的用户接口上不再需要传入Context,可以和非Android环境下的方案保持接口一致
* Created by yoyoqin on 2016/6/29.
*/
public class EvnSet {
private EvnSet INSTANCE;
private Context context;
public synchronized EvnSet getInstance()
{
if (INSTANCE == null)
{
INSTANCE = new EvnSet();
}
return INSTANCE;
}
public void setContext(Context context)
{
this.context = context;
}
public Context getContext()
{
return this.context;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/facade/src/androidTest/java/com/tencent/wstt/gt/facade/ApplicationTest.java | facade/src/androidTest/java/com/tencent/wstt/gt/facade/ApplicationTest.java | package com.tencent.wstt.gt.facade;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/log/src/main/java/com/tencent/wstt/gt/log/logcat/LogLine.java | log/src/main/java/com/tencent/wstt/gt/log/logcat/LogLine.java | package com.tencent.wstt.gt.log.logcat;
import android.text.TextUtils;
import android.util.Log;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogLine {
public static final String LOGCAT_DATE_FORMAT = "MM-dd HH:mm:ss.SSS";
private static final int TIMESTAMP_LENGTH = 19;
private static Pattern logPattern = Pattern.compile(
// log level
"(\\w)" +
"/" +
// tag
"([^(]+)" +
"\\(\\s*" +
// pid
"(\\d+)" +
// optional weird number that only occurs on ZTE blade
"(?:\\*\\s*\\d+)?" +
"\\): ");
private int logLevel;
private String tag;
private String logOutput;
private int processId = -1;
private String timestamp;
private boolean expanded = false;
private boolean highlighted = false;
public CharSequence getOriginalLine() {
if (logLevel == -1) { // starter line like "begin of log etc. etc."
return logOutput;
}
StringBuilder stringBuilder = new StringBuilder();
if (timestamp != null) {
stringBuilder.append(timestamp).append(' ');
}
stringBuilder.append(convertLogLevelToChar(logLevel))
.append('/')
.append(tag)
.append('(')
.append(processId)
.append("): ")
.append(logOutput);
return stringBuilder;
}
public int getLogLevel() {
return logLevel;
}
public void setLogLevel(int logLevel) {
this.logLevel = logLevel;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getLogOutput() {
return logOutput;
}
public void setLogOutput(String logOutput) {
this.logOutput = logOutput;
}
public int getProcessId() {
return processId;
}
public void setProcessId(int processId) {
this.processId = processId;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public boolean isExpanded() {
return expanded;
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
public boolean isHighlighted() {
return highlighted;
}
public void setHighlighted(boolean highlighted) {
this.highlighted = highlighted;
}
public static LogLine newLogLine(String originalLine, boolean expanded) {
LogLine logLine = new LogLine();
logLine.setExpanded(expanded);
int startIdx = 0;
// if the first char is a digit, then this starts out with a timestamp
// otherwise, it's a legacy log or the beginning of the log output or something
if (!TextUtils.isEmpty(originalLine)
&& Character.isDigit(originalLine.charAt(0))
&& originalLine.length() >= TIMESTAMP_LENGTH) {
String timestamp = originalLine.substring(0, TIMESTAMP_LENGTH - 1);
logLine.setTimestamp(timestamp);
startIdx = TIMESTAMP_LENGTH; // cut off timestamp
}
Matcher matcher = logPattern.matcher(originalLine);
if (matcher.find(startIdx)) {
char logLevelChar = matcher.group(1).charAt(0);
logLine.setLogLevel(convertCharToLogLevel(logLevelChar));
logLine.setTag(matcher.group(2));
logLine.setProcessId(Integer.parseInt(matcher.group(3)));
logLine.setLogOutput(originalLine.substring(matcher.end()));
} else {
logLine.setLogOutput(originalLine);
logLine.setLogLevel(-1);
}
return logLine;
}
public static int convertCharToLogLevel(char logLevelChar) {
switch (logLevelChar) {
case 'D':
return Log.DEBUG;
case 'E':
return Log.ERROR;
case 'I':
return Log.INFO;
case 'V':
return Log.VERBOSE;
case 'W':
return Log.WARN;
}
return -1;
}
public static char convertLogLevelToChar(int logLevel) {
switch (logLevel) {
case Log.DEBUG:
return 'D';
case Log.ERROR:
return 'E';
case Log.INFO:
return 'I';
case Log.VERBOSE:
return 'V';
case Log.WARN:
return 'W';
}
return ' ';
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/log/src/main/java/com/tencent/wstt/gt/log/logcat/LogcatReader.java | log/src/main/java/com/tencent/wstt/gt/log/logcat/LogcatReader.java | package com.tencent.wstt.gt.log.logcat;
import java.io.IOException;
import java.util.List;
public interface LogcatReader {
/**
* Read a single log line, ala BufferedReader.readLine().
* @return
* @throws IOException
*/
public String readLine() throws IOException;
/**
* Kill the reader and close all resources without throwing any exceptions.
*/
public void killQuietly();
public boolean readyToRecord();
public List<Process> getProcesses();
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/log/src/main/java/com/tencent/wstt/gt/log/logcat/LogcatHelper.java | log/src/main/java/com/tencent/wstt/gt/log/logcat/LogcatHelper.java | package com.tencent.wstt.gt.log.logcat;
import com.tencent.wstt.gt.util.RuntimeHelper;
import com.tencent.wstt.gt.util.VersionHelper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LogcatHelper {
public static final String BUFFER_MAIN = "main";
public static final String BUFFER_EVENTS = "events";
public static final String BUFFER_RADIO = "radio";
public static Process getLogcatProcess(String buffer) throws IOException {
List<String> args = getLogcatArgs(buffer);
Process process = RuntimeHelper.exec(args);
return process;
}
private static List<String> getLogcatArgs(String buffer) {
List<String> args = new ArrayList<String>(Arrays.asList("logcat", "-v", "time"));
// for some reason, adding -b main excludes log output from
// AndroidRuntime runtime exceptions,
// whereas just leaving it blank keeps them in. So do not specify the
// buffer if it is "main"
if (!buffer.equals(BUFFER_MAIN)) {
args.add("-b");
args.add(buffer);
}
return args;
}
public static String getLastLogLine(String buffer) {
Process dumpLogcatProcess = null;
BufferedReader reader = null;
String result = null;
try {
List<String> args = getLogcatArgs(buffer);
args.add("-d"); // -d just dumps the whole thing
dumpLogcatProcess = RuntimeHelper.exec(args);
reader = new BufferedReader(new InputStreamReader(dumpLogcatProcess.getInputStream()), 8192);
String line;
while ((line = reader.readLine()) != null) {
result = line;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dumpLogcatProcess != null) {
RuntimeHelper.destroy(dumpLogcatProcess);
}
// post-jellybean, we just kill the process, so there's no need
// to close the bufferedReader. Anyway, it just hangs.
if (VersionHelper.getVersionSdkIntCompat() < VersionHelper.VERSION_JELLYBEAN && reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/log/src/main/java/com/tencent/wstt/gt/log/logcat/MultipleLogcatReader.java | log/src/main/java/com/tencent/wstt/gt/log/logcat/MultipleLogcatReader.java | package com.tencent.wstt.gt.log.logcat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import android.os.AsyncTask;
/**
* Combines multipe buffered readers into a single reader that merges all input synchronously.
*/
public class MultipleLogcatReader extends AbsLogcatReader {
private static final String DUMMY_NULL = new String("");
private List<ReaderThread> readerThreads = new LinkedList<ReaderThread>();
private BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1);
public MultipleLogcatReader(boolean recordingMode,
Map<String,String> lastLines) throws IOException {
super(recordingMode);
// read from all three buffers at once
for (Entry<String,String> entry : lastLines.entrySet()) {
String logBuffer = entry.getKey();
String lastLine = entry.getValue();
ReaderThread readerThread = new ReaderThread(logBuffer, lastLine);
readerThread.start();
readerThreads.add(readerThread);
}
}
public String readLine() throws IOException {
try {
String value = queue.take();
if (value != DUMMY_NULL) {
return value;
}
} catch (InterruptedException e) {
}
return null;
}
@Override
public boolean readyToRecord() {
for (ReaderThread thread : readerThreads) {
if (!thread.reader.readyToRecord()) {
return false;
}
}
return true;
}
@Override
public void killQuietly() {
for (ReaderThread thread : readerThreads) {
thread.killed = true;
}
// do in background, because otherwise we might hang
new AsyncTask<Void, Void, Void>(){
@Override
protected Void doInBackground(Void... params) {
for (ReaderThread thread : readerThreads) {
thread.reader.killQuietly();
}
queue.offer(DUMMY_NULL);
return null;
}
}.execute((Void)null);
}
@Override
public List<Process> getProcesses() {
List<Process> result = new ArrayList<Process>();
for (ReaderThread thread : readerThreads) {
result.addAll(thread.reader.getProcesses());
}
return result;
}
private class ReaderThread extends Thread {
SingleLogcatReader reader;
private boolean killed;
public ReaderThread(String logBuffer, String lastLine) throws IOException {
this.reader = new SingleLogcatReader(recordingMode, logBuffer, lastLine);
}
@Override
public void run() {
String line;
try {
while (!killed && (line = reader.readLine()) != null && !killed) {
queue.put(line);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/log/src/main/java/com/tencent/wstt/gt/log/logcat/package-info.java | log/src/main/java/com/tencent/wstt/gt/log/logcat/package-info.java | /**
<b>本包的职责:</b><br>
* 1、LogCat日志解析模块,从CatLog精简而来
*/
package com.tencent.wstt.gt.log.logcat; | java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/log/src/main/java/com/tencent/wstt/gt/log/logcat/AbsLogcatReader.java | log/src/main/java/com/tencent/wstt/gt/log/logcat/AbsLogcatReader.java | package com.tencent.wstt.gt.log.logcat;
public abstract class AbsLogcatReader implements LogcatReader {
protected boolean recordingMode;
public AbsLogcatReader(boolean recordingMode) {
this.recordingMode = recordingMode;
}
public boolean isRecordingMode() {
return recordingMode;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/log/src/main/java/com/tencent/wstt/gt/log/logcat/SingleLogcatReader.java | log/src/main/java/com/tencent/wstt/gt/log/logcat/SingleLogcatReader.java | package com.tencent.wstt.gt.log.logcat;
import android.text.TextUtils;
import com.tencent.wstt.gt.util.RuntimeHelper;
import com.tencent.wstt.gt.util.VersionHelper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;
public class SingleLogcatReader extends AbsLogcatReader {
private Process logcatProcess;
private BufferedReader bufferedReader;
private String logBuffer;
private String lastLine;
public SingleLogcatReader(boolean recordingMode, String logBuffer, String lastLine) throws IOException {
super(recordingMode);
this.logBuffer = logBuffer;
this.lastLine = lastLine;
init();
}
private void init() throws IOException {
// use the "time" log so we can see what time the logs were logged at
logcatProcess = LogcatHelper.getLogcatProcess(logBuffer);
bufferedReader = new BufferedReader(new InputStreamReader(logcatProcess
.getInputStream()), 8192);
}
public String getLogBuffer() {
return logBuffer;
}
@Override
public void killQuietly() {
if (logcatProcess != null) {
RuntimeHelper.destroy(logcatProcess);
}
// post-jellybean, we just kill the process, so there's no need
// to close the bufferedReader. Anyway, it just hangs.
if (VersionHelper.getVersionSdkIntCompat() < VersionHelper.VERSION_JELLYBEAN
&& bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public String readLine() throws IOException {
String line = bufferedReader.readLine();
if (recordingMode && lastLine != null) { // still skipping past the 'last line'
if (lastLine.equals(line) || isAfterLastTime(line)) {
lastLine = null; // indicates we've passed the last line
}
}
return line;
}
private boolean isAfterLastTime(String line) {
// doing a string comparison is sufficient to determine whether this line is chronologically
// after the last line, because the format they use is exactly the same and
// lists larger time period before smaller ones
return isDatedLogLine(lastLine) && isDatedLogLine(line) && line.compareTo(lastLine) > 0;
}
private boolean isDatedLogLine(String line) {
// 18 is the size of the logcat timestamp
return (!TextUtils.isEmpty(line) && line.length() >= 18 && Character.isDigit(line.charAt(0)));
}
@Override
public boolean readyToRecord() {
if (!recordingMode) {
return false;
}
return lastLine == null;
}
@Override
public List<Process> getProcesses() {
return Collections.singletonList(logcatProcess);
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/log/src/main/java/com/tencent/wstt/gt/log/logcat/LogcatReaderLoader.java | log/src/main/java/com/tencent/wstt/gt/log/logcat/LogcatReaderLoader.java | package com.tencent.wstt.gt.log.logcat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
public class LogcatReaderLoader implements Parcelable {
private Map<String,String> lastLines = new HashMap<String, String>();
private boolean recordingMode;
private boolean multiple;
private LogcatReaderLoader(Parcel in) {
this.recordingMode = in.readInt() == 1;
this.multiple = in.readInt() == 1;
Bundle bundle = in.readBundle();
for (String key : bundle.keySet()) {
lastLines.put(key, bundle.getString(key));
}
}
private LogcatReaderLoader(List<String> buffers, boolean recordingMode) {
this.recordingMode = recordingMode;
this.multiple = buffers.size() > 1;
for (String buffer : buffers) {
// no need to grab the last line if this isn't recording mode
String lastLine = recordingMode ? LogcatHelper.getLastLogLine(buffer) : null;
lastLines.put(buffer, lastLine);
}
}
public LogcatReader loadReader() throws IOException {
LogcatReader reader;
if (!multiple) {
// single reader
String buffer = lastLines.keySet().iterator().next();
String lastLine = lastLines.values().iterator().next();
reader = new SingleLogcatReader(recordingMode, buffer, lastLine);
} else {
// multiple reader
reader = new MultipleLogcatReader(recordingMode, lastLines);
}
return reader;
}
public static LogcatReaderLoader create(Context context, boolean recordingMode) {
List<String> buffers = new ArrayList<String>();
buffers.add("main");
LogcatReaderLoader loader = new LogcatReaderLoader(buffers, recordingMode);
return loader;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(recordingMode ? 1 : 0);
dest.writeInt(multiple ? 1 : 0);
Bundle bundle = new Bundle();
for (Entry<String,String> entry : lastLines.entrySet()) {
bundle.putString(entry.getKey(), entry.getValue());
}
dest.writeBundle(bundle);
}
public static final Creator<LogcatReaderLoader> CREATOR = new Creator<LogcatReaderLoader>() {
public LogcatReaderLoader createFromParcel(Parcel in) {
return new LogcatReaderLoader(in);
}
public LogcatReaderLoader[] newArray(int size) {
return new LogcatReaderLoader[size];
}
};
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/util/ProcessCPUUtils.java | datasourceOutOfAndroid/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 com.tencent.wstt.gt.util.DoubleUtils;
import com.tencent.wstt.gt.util.FileUtil;
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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/util/package-info.java | datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/util/package-info.java | /**
* @author yoyoqin
* 从APT和GT中剥离出的不依赖于Android SDK的基本性能指标采集实现的工具包
*/
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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/util/UidNETUtils.java | datasourceOutOfAndroid/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 com.tencent.wstt.gt.util.FileUtil;
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
*/
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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/util/SFUtils.java | datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/util/SFUtils.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 com.tencent.wstt.gt.log.logcat.LogLine;
import com.tencent.wstt.gt.util.RuntimeHelper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class SFUtils {
private static Set<Integer> pids = new HashSet<Integer>(2);
private static Map<Integer, BlockingQueue<Integer>> queues = new HashMap<Integer, BlockingQueue<Integer>>(2);
private static boolean killed = true;
private static Process dumpLogcatProcess;
/**
* 启动一个进程的卡顿帧数采集
* @param pid 进程号
* @return
*/
public static BlockingQueue<Integer> startSampleSF(int pid)
{
synchronized (SFUtils.class)
{
BlockingQueue<Integer> result = queues.get(pid);
if (result != null)
{
return result;
}
result = new ArrayBlockingQueue<Integer>(2);
pids.add(pid);
queues.put(pid, result);
if (dumpLogcatProcess == null && killed)
{
killed = false;
new Thread(new Runnable() {
@Override
public void run() {
try {
filterSF();
} catch (NumberFormatException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}, "GTSFRunner").start();
}
return result;
}
}
/**
* 停止一个进程的卡顿帧数采集
* @param pid 进程号
* @return
*/
public static void stopSampleSF(int pid)
{
synchronized (SFUtils.class)
{
pids.remove(pid);
queues.remove(pid);
}
if (pids.size() == 0) killProcess();
}
private static void filterSF() throws NumberFormatException, IOException {
List<String> args = new ArrayList<String>(
Arrays.asList("logcat", "-v", "time", "Choreographer:I", "*:S"));
dumpLogcatProcess = RuntimeHelper.exec(args);
BufferedReader reader = new BufferedReader(
new InputStreamReader(dumpLogcatProcess.getInputStream()), 8192);
String line;
while ((line = reader.readLine()) != null && !killed) {
// filter "The application may be doing too much work on its main thread."
if (!line.contains("uch work on its main t")) {
continue;
}
int pid = LogLine.newLogLine(line, false).getProcessId();
if (! pids.contains(Integer.valueOf(pid))) {
continue;
}
line = line.substring(50, line.length() - 71);
Integer value = Integer.parseInt(line.trim());
BlockingQueue<Integer> queue = queues.get(pid);
queue.offer(value);
}
killProcess();
}
private static void killProcess() {
if (!killed) {
synchronized (SFUtils.class) {
if (!killed) {
if (dumpLogcatProcess != null) {
RuntimeHelper.destroy(dumpLogcatProcess);
dumpLogcatProcess = null;
}
killed = true;
}
}
}
}
/**
* 检查卡帧设置是否有效
* @return
*/
public static boolean check() {
String cmd = "getprop debug.choreographer.skipwarning";
ProcessBuilder execBuilder = new ProcessBuilder("sh", "-c", cmd);
execBuilder.redirectErrorStream(true);
boolean flag = false;
try {
Process p = execBuilder.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
if (line.compareTo("1") == 0) {
flag = true;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* 设置卡帧阈值为1
* @return
*/
public static void modify() {
String cmd = "setprop debug.choreographer.skipwarning 1";
ProcessBuilder execBuilder = new ProcessBuilder("su", "-c", cmd);
execBuilder.redirectErrorStream(true);
try {
execBuilder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 恢复卡帧设置为30
*/
public static void recover() {
String cmd = "setprop debug.choreographer.skipwarning 30";
ProcessBuilder execBuilder = new ProcessBuilder("su", "-c", cmd);
execBuilder.redirectErrorStream(true);
try {
execBuilder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 软启动以使卡帧设置生效
*/
public static void restart()
{
String cmd = "setprop ctl.restart surfaceflinger; setprop ctl.restart zygote";
ProcessBuilder execBuilder = new ProcessBuilder("su", "-c", cmd);
execBuilder.redirectErrorStream(true);
try {
execBuilder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 基于标准流畅度为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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/util/CPUUtils.java | datasourceOutOfAndroid/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 com.tencent.wstt.gt.util.DoubleUtils;
import com.tencent.wstt.gt.util.FileUtil;
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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/util/MEMUtils.java | datasourceOutOfAndroid/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 java.lang.reflect.Method;
/**
* 内存信息工具类。
*/
public class MEMUtils {
/**
* 获取内存信息:total、free、buffers、cached,单位MB
*
* @return 内存信息{total,free,buffers,cached}
*/
public static long[] getPhoneMem() {
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;
}
/**
* TODO 通过解析dumpsys meminfo方式获取进程内存的PSS和Private Dirty数据
* =============================================================================================
** MEMINFO in pid 2057 [android.process.media] **
Pss Private Private Swapped Heap Heap Heap
Total Dirty Clean Dirty Size Alloc Free
------ ------ ------ ------ ------ ------ ------
Native Heap 2762 2692 0 0 5888 4326 1561
Dalvik Heap 976 944 0 0 1150 923 227
Dalvik Other 317 316 0 0
Stack 96 96 0 0
Other dev 4 0 4 0
.so mmap 413 56 16 0
.apk mmap 126 0 84 0
.dex mmap 856 8 848 0
.oat mmap 1267 0 400 0
.art mmap 980 616 0 0
Other mmap 124 8 64 0
Unknown 73 72 0 0
TOTAL 7994 4808 1416 0 7038 5249 1788
*==============================================================================================
*
* @param pname 进程名
* @return {nativePrivateDirty,dalvikPrivateDirty,TotalPrivateDirty}
*/
public static long[] getProcessMem(String pname) {
return null;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/util/NETUtils.java | datasourceOutOfAndroid/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;
public class NETUtils {
private static final double B2K = 1024.00d;
/**
* TODO 获取当前流量值
* @return {t_add_wifi, r_add_wifi, t_add_3G, r_add_3G, t_add_2G, r_add_2G}
*/
public static double[] getNetTxRxKB() {
double[] result = new double[6];
return result;
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/util/FrameUtils.java | datasourceOutOfAndroid/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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/engine/NETTimerTask.java | datasourceOutOfAndroid/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 com.tencent.wstt.gt.datasource.util.NETUtils;
import java.util.TimerTask;
/**
* 整机流量采集引擎
*/
public class NETTimerTask extends TimerTask {
private DataRefreshListener<Double[]> dataRefreshListener;
/**
* 构造方法
* @param dataRefreshListener 数据的监听器
*/
public NETTimerTask(DataRefreshListener<Double[]> dataRefreshListener)
{
this.dataRefreshListener = dataRefreshListener;
}
public void run() {
double result[] = NETUtils.getNetTxRxKB();
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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/engine/MEMTimerTask.java | datasourceOutOfAndroid/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.getPhoneMem();
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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/engine/FPSTimerTask.java | datasourceOutOfAndroid/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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/engine/package-info.java | datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/engine/package-info.java | /**
* @author yoyoqin
* 性能数据采集引擎,不依赖于Android SDK,供非Android环境自动化脚本直接使用或进一步封装
*/
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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/engine/CPUTimerTask.java | datasourceOutOfAndroid/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 {
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]));
jiffiesFreshListener.onRefresh(System.currentTimeMillis(), Long.valueOf((long)result[1]));
}
else // 整机的
{
double result = CPUUtils.getUsage(interval);
cpuFreshListener.onRefresh(System.currentTimeMillis(), Double.valueOf(result));
}
}
public void stop()
{
this.cancel();
}
} | java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/engine/SMTimerTask.java | datasourceOutOfAndroid/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.SFUtils;
import java.lang.reflect.Field;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 流畅度数据采集引擎
*/
public class SMTimerTask extends TimerTask {
private boolean hasSu = true;
private int standardSM = 60; // 标准的SM值,如果是未来兼容VR设备的手机,也可能达到120或更高
private boolean isGetPeriod = false; // 是否已获取执行间隔值
private long thisPeriod = 1000; // 默认1000ms,在初次执行时要通过反射方法在超类中获取真实值
private int pid;
private DataRefreshListener<Long> dataRefreshListener;
private BlockingQueue<Integer> queue;
private AtomicInteger count = new AtomicInteger(0);
private boolean pause = false;
/**
* 构造方法
* @param pid 指定进程号
* @param dataRefreshListener 数据的监听器
* @param hasSu 是否已root,事实上获取流畅度数值必须root
*/
public SMTimerTask(int pid, DataRefreshListener<Long> dataRefreshListener, boolean hasSu)
{
this.pid = pid;
this.dataRefreshListener = dataRefreshListener;
this.hasSu = hasSu;
queue = SFUtils.startSampleSF(pid);
Thread dataCountThread = new Thread("GTSMRunner") {
@Override
public void run() {
while (!pause)
{
try {
int value = queue.take();
count.addAndGet(value);
} catch (InterruptedException e) {
return;
}
}
}
};
dataCountThread.start();
}
public boolean isHasSu() {
return hasSu;
}
public void setHasSu(boolean hasSu) {
this.hasSu = hasSu;
}
public int getStandardSM() {
return standardSM;
}
/**
* 设置标准SM值
* @param standardSM 必须大于0,否则默认设置为60
*/
public void setStandardSM(int standardSM) {
this.standardSM = standardSM <= 0 ? 60 : standardSM;
}
/*
* 主循环,1s执行一次
* @see java.util.TimerTask#run()
*/
public void run() {
/*
* Timer的启动无法避免,所以这里加root保护
* 若未root,直接返回,减少空消耗
*/
if (! hasSu)
{
return;
}
// Task的执行采样间隔
if (! isGetPeriod)
{
Class<?> clz = TimerTask.class;
Field superPeriod = null;
try {
superPeriod = clz.getDeclaredField("period");
superPeriod.setAccessible(true);
thisPeriod = superPeriod.getLong(this);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
isGetPeriod = true;
}
long tempStandardSM = standardSM * thisPeriod / 1000; // 比如standardSM=60,scheduled=500,tempStandardSM的值就是30
int x = count.getAndSet(0);
// 卡顿大于60时,要将之前几次SM计数做修正
if (x > tempStandardSM) {
long n = x / tempStandardSM;
long v = x % tempStandardSM;
for (int i = 0; i < n; i++) {
dataRefreshListener.onRefresh(System.currentTimeMillis() - thisPeriod * i , Long.valueOf(0));
}
dataRefreshListener.onRefresh(System.currentTimeMillis(), Long.valueOf(60 - v * 1000 / thisPeriod));
} else {
dataRefreshListener.onRefresh(System.currentTimeMillis(), Long.valueOf(60 - x * 1000 / thisPeriod));
}
}
public void stop()
{
pause = true;
this.cancel();
SFUtils.stopSampleSF(pid);
}
} | java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/engine/DataRefreshListener.java | datasourceOutOfAndroid/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 interface DataRefreshListener<T> {
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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/engine/UidNETTimerTask.java | datasourceOutOfAndroid/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/datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/engine/ProcessMemTimerTask.java | datasourceOutOfAndroid/src/main/java/com/tencent/wstt/gt/datasource/engine/ProcessMemTimerTask.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;
/**
* 进程的PSS维度内存采集引擎
*/
public class ProcessMemTimerTask extends TimerTask {
private String processName;
private DataRefreshListener<Long[]> dataRefreshListener;
/**
* 构造方法
* @param processName 指定进程号
* @param dataRefreshListener 数据的监听器
*/
public ProcessMemTimerTask(String processName, DataRefreshListener<Long[]> dataRefreshListener)
{
this.processName = processName;
this.dataRefreshListener = dataRefreshListener;
}
public void run() {
long result[] = MEMUtils.getProcessMem(processName);
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/datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/AllTest.java | datasourceOutOfAndroid/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 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.MEMTimerTask;
import com.tencent.wstt.gt.datasource.engine.NETTimerTask;
import com.tencent.wstt.gt.datasource.engine.ProcessMemTimerTask;
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(android.os.Process.myPid(), new DataRefreshListener<Long>() {
@Override
public void onRefresh(long time, Long data) {
System.out.println("SM:" + data);
}
}, true);
timerSM.schedule(taskSM, 0, 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);
ProcessMemTimerTask task5 = new ProcessMemTimerTask("com.android.systemui",
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);
NETTimerTask task7 = new NETTimerTask(
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);
// 需要先选择适合自己环境的采集方案
if (!UidNETUtils.test(-1)) {
UidNETUtils.Case c = new UidNETUtils.CaseTrafficStats();
if (!c.test(-1)) c = new UidNETUtils.CaseInvalid();
UidNETUtils.setSampleCase(c);
}
UidNETTimerTask task8 = 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(task8, 0, 1000);
Thread.sleep(20000);
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/SMTest.java | datasourceOutOfAndroid/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.SFUtils;
import org.junit.Assert;
import org.junit.Test;
import java.util.Timer;
public class SMTest {
@Test
public void testSmBase() throws InterruptedException
{
if (!SFUtils.check())
{
SFUtils.modify();
SFUtils.restart();
return;
}
Assert.assertTrue(SFUtils.check());
Timer timer = new Timer();
SMTimerTask task = new SMTimerTask(0, new DataRefreshListener<Long>(){
@Override
public void onRefresh(long time, Long data) {
System.out.println(data);
}}, true);
timer.schedule(task, 0, 1000);
Thread.sleep(50000);
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/NETTest.java | datasourceOutOfAndroid/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 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(
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 |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/package-info.java | datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/package-info.java | /**
* @author yoyoqin
*
*/
package com.tencent.wstt.gt.datasource; | java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/ApplicationTest.java | datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/ApplicationTest.java | package com.tencent.wstt.gt.datasource;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/MEMTest.java | datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/MEMTest.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.MEMTimerTask;
import com.tencent.wstt.gt.datasource.engine.ProcessMemTimerTask;
import org.junit.Test;
import java.util.Timer;
public class MEMTest {
@Test
public void testMem() throws InterruptedException
{
Timer timer = new Timer();
MEMTimerTask task = new MEMTimerTask(
new DataRefreshListener<Long[]>(){
@Override
public void onRefresh(long time, Long[] data) {
System.out.println(data[0] + "/" + data[1] + "/" + data[2]+ "/" + data[3]);
}});
timer.schedule(task, 0, 1000);
Thread.sleep(10000);
}
@Test
public void testProcessMem() throws InterruptedException
{
Timer timer = new Timer();
ProcessMemTimerTask task = new ProcessMemTimerTask("com.android.systemui",
new DataRefreshListener<Long[]>(){
@Override
public void onRefresh(long time, Long[] data) {
System.out.println(data[0] + "/" + data[1] + "/" + data[2]);
}});
timer.schedule(task, 0, 1000);
Thread.sleep(10000);
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/UseOutParamTest.java | datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/UseOutParamTest.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.runner.AndroidJUnit4;
import com.tencent.wstt.gt.datasource.engine.CPUTimerTask;
import com.tencent.wstt.gt.datasource.engine.DataRefreshListener;
import com.tencent.wstt.gt.datasource.engine.MEMTimerTask;
import com.tencent.wstt.gt.monitor.model.AbsOutParam;
import com.tencent.wstt.gt.monitor.model.TimeBean;
import com.tencent.wstt.gt.monitor.simple.DoubleOutParam;
import com.tencent.wstt.gt.monitor.simple.DoubleThresholdListener;
import com.tencent.wstt.gt.monitor.simple.LongOutParam;
import com.tencent.wstt.gt.monitor.simple.LongThresholdListener;
import com.tencent.wstt.gt.monitor.threshold.IGTComparator;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Timer;
/**
* Created by yoyoqin on 2016/5/31.
*/
@RunWith(AndroidJUnit4.class)
public class UseOutParamTest {
/**
* 利用出参的阈值能力对超过10%的CPU进行告警
*/
@Test
public void testCPUWithOutParamThreshold() throws InterruptedException
{
// 创建用于监控CPU指标的对象
final DoubleOutParam cpuOutParam = new DoubleOutParam(null, "CPU");
cpuOutParam.setRecord(true); // 启动记录
cpuOutParam.setMonitor(true); // 启动告警监控
/*
* 设置CPU超出10的告警阈值
*/
cpuOutParam.addThresholdListener(new DoubleThresholdListener<AbsOutParam<Double>>(10.0d, 1, null, 0, null, 0) {
@Override
public void onHigherThan(AbsOutParam<Double> src, Double data, IGTComparator<Double> c) {
// 当CPU超过10时,触发该回调,输出下面的信息到控制台
System.out.println("CPU higher than "+ c.getTarget() + ":" + data);
}
@Override
public void onLowerThan(AbsOutParam<Double> src, Double data, IGTComparator<Double> c) {
}
@Override
public void onEquals(AbsOutParam<Double> src, Double data, IGTComparator<Double> c) {
}
});
/*
* 初始化CPU数据采集任务,监听中使用前面创建的cpuOutParam对象对CPU数据进行监控
* 进程号填0,关注的即整机的CPU
*/
CPUTimerTask task = new CPUTimerTask(0, 1000,
new DataRefreshListener<Double>(){
@Override
public void onRefresh(long time, Double data) {
cpuOutParam.setValue(time, Double.valueOf(data));
System.out.println("CPU:" + data);
}},null);
// 启动定时任务,注意因为任务本身有1000ms的时间间隔,所以定时任务的间隔填最小的1ms
// CPU指标的采集之所以如此设计,是为了和其他指标采集方式保持一致
Timer timer = new Timer();
timer.schedule(task, 0, 1);
Thread.sleep(10000);
// 打印此时已记录的CPU历史数据
for (TimeBean<Double> timeBean : cpuOutParam.getRecordList())
{
System.out.println("CPU:" + timeBean.data + " Time:" + timeBean.time);
}
}
/**
* 利用出参的阈值能力对手机内存低于800MB时进行告警
*/
@Test
public void testMEMWithOutParamThreshold() throws InterruptedException
{
final LongOutParam memOutParam = new LongOutParam(null, "MEM");
final LongOutParam memAllOutParam = new LongOutParam(null, "Total");
final LongOutParam memFreeOutParam = new LongOutParam(null, "Free");
memFreeOutParam.setRecord(true); // 启动记录
memFreeOutParam.setMonitor(true); // 启动告警监控
// 设置Free内存低于800M的告警阈值
memFreeOutParam.addThresholdListener(new LongThresholdListener<AbsOutParam<Long>>(null, 0, 800L, 1, null, 0) {
@Override
public void onHigherThan(AbsOutParam<Long> src, Long data, IGTComparator<Long> c) {
}
@Override
public void onLowerThan(AbsOutParam<Long> src, Long data, IGTComparator<Long> c) {
// 当Free内存低于800MB时会触发此告警向控制台输出打印信息
System.out.println("MEM Free lower than "+ c.getTarget() + ", " + c.getCount() + " times:" + data);
}
@Override
public void onEquals(AbsOutParam<Long> src, Long data, IGTComparator<Long> c) {
}
});
memOutParam.addChild(memAllOutParam);
memOutParam.addChild(memFreeOutParam);
// 对手机整机的内存数据进行监控
MEMTimerTask task = new MEMTimerTask(new DataRefreshListener<Long[]>(){
@Override
public void onRefresh(long time, Long[] data) {
memOutParam.getChild(0).setValue(time, data[0]);
memOutParam.getChild(1).setValue(time, data[1] + data[2] + data[3]);
System.out.println("MEM Free/Total:" + (data[1] + data[2] + data[3]) + "/" + data[0]);
}});
// 启动定时任务,因为内存数据是即时值,所以定时1000ms采集一次
Timer timer = new Timer();
timer.schedule(task, 0, 1000);
Thread.sleep(10000);
// 打印此时已记录的剩余内存历史数据
for (TimeBean<Long> timeBean : memOutParam.getChild(1).getRecordList())
{
System.out.println("MEM Free:" + timeBean.data + " Time:" + timeBean.time);
}
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/CPUTest.java | datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/CPUTest.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.CPUTimerTask;
import com.tencent.wstt.gt.datasource.engine.DataRefreshListener;
import org.junit.Test;
import java.util.Timer;
public class CPUTest {
@Test
public void testCPU() throws InterruptedException
{
Timer timer = new Timer();
// 进程号填0,关注的即整机的CPU
CPUTimerTask task = new CPUTimerTask(0, 1000,
new DataRefreshListener<Double>(){
@Override
public void onRefresh(long time, Double data) {
System.out.println("CPU:" + data);
}},null);
timer.schedule(task, 0, 1);
Thread.sleep(10000);
}
@Test
public void testProcessCPU() throws InterruptedException
{
Timer timer = new Timer();
// 测试代码中以自身进程数据
CPUTimerTask task = new CPUTimerTask(android.os.Process.myPid(), 1000,
new DataRefreshListener<Double>(){
@Override
public void onRefresh(long time, Double data) {
System.out.println("CPU:" + data);
}},
new DataRefreshListener<Long>(){
@Override
public void onRefresh(long time, Long data) {
System.out.println("Jiffies:" + data);
}});
timer.schedule(task, 0, 1);
Thread.sleep(10000);
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
r551/GTTools | https://github.com/r551/GTTools/blob/e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5/datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/FPSTest.java | datasourceOutOfAndroid/src/androidTest/java/com/tencent/wstt/gt/datasource/FPSTest.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.FPSTimerTask;
import org.junit.Test;
import java.util.Timer;
public class FPSTest {
@Test
public void testFpsBase() throws InterruptedException
{
Timer timer = new Timer();
FPSTimerTask task = new FPSTimerTask(new DataRefreshListener<Long>(){
@Override
public void onRefresh(long time, Long data) {
System.out.println(data);
}}, true);
timer.schedule(task, 0, 1000);
Thread.sleep(10000);
}
}
| java | MIT | e52c7da61b6af25c3c2d4b47b6ac8828b0e4cbf5 | 2026-01-05T02:37:34.026955Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/controller/NotifyItemChecked.java | library/src/main/java/com/developer/filepicker/controller/NotifyItemChecked.java | package com.developer.filepicker.controller;
/**
* @author akshay sunil masram
*/
public interface NotifyItemChecked {
void notifyCheckBoxIsClicked();
} | java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/controller/DialogSelectionListener.java | library/src/main/java/com/developer/filepicker/controller/DialogSelectionListener.java | package com.developer.filepicker.controller;
/**
* @author akshay sunil masram
*/
public interface DialogSelectionListener {
void onSelectedFilePaths(String[] files);
} | java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/controller/adapters/FileListAdapter.java | library/src/main/java/com/developer/filepicker/controller/adapters/FileListAdapter.java | package com.developer.filepicker.controller.adapters;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.developer.filepicker.R;
import com.developer.filepicker.controller.NotifyItemChecked;
import com.developer.filepicker.model.DialogConfigs;
import com.developer.filepicker.model.DialogProperties;
import com.developer.filepicker.model.FileListItem;
import com.developer.filepicker.model.MarkedItemList;
import com.developer.filepicker.widget.MaterialCheckbox;
import com.developer.filepicker.widget.OnCheckedChangeListener;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
/**
* @author akshay sunil masram
*/
public class FileListAdapter extends BaseAdapter {
private static final String TAG = FileListAdapter.class.getSimpleName();
private ArrayList<FileListItem> listItem;
private Context context;
private DialogProperties properties;
private NotifyItemChecked notifyItemChecked;
public FileListAdapter(ArrayList<FileListItem> listItem, Context context,
DialogProperties properties) {
this.listItem = listItem;
this.context = context;
this.properties = properties;
}
@Override
public int getCount() {
return listItem.size();
}
@Override
public FileListItem getItem(int i) {
return listItem.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final ViewHolder holder;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.dialog_file_list_item,
viewGroup, false);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
final FileListItem item = listItem.get(i);
if (MarkedItemList.hasItem(item.getLocation())) {
Animation animation = AnimationUtils.loadAnimation(context,
R.anim.marked_item_animation);
view.setAnimation(animation);
} else {
Animation animation = AnimationUtils.loadAnimation(context,
R.anim.unmarked_item_animation);
view.setAnimation(animation);
}
if (item.isDirectory()) {
holder.type_icon.setImageResource(R.mipmap.ic_type_folder);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.type_icon.setColorFilter(context.getResources()
.getColor(R.color.colorPrimary, context.getTheme()));
} else {
holder.type_icon.setColorFilter(context.getResources()
.getColor(R.color.colorPrimary));
}
if (properties.selection_type == DialogConfigs.FILE_SELECT) {
holder.checkbox.setVisibility(View.INVISIBLE);
} else {
holder.checkbox.setVisibility(View.VISIBLE);
}
} else {
holder.type_icon.setImageResource(R.mipmap.ic_type_file);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.type_icon.setColorFilter(context.getResources()
.getColor(R.color.colorAccent, context.getTheme()));
} else {
holder.type_icon.setColorFilter(context.getResources()
.getColor(R.color.colorAccent));
}
if (properties.selection_type == DialogConfigs.DIR_SELECT) {
holder.checkbox.setVisibility(View.INVISIBLE);
} else {
holder.checkbox.setVisibility(View.VISIBLE);
}
}
holder.type_icon.setContentDescription(item.getFilename());
holder.name.setText(item.getFilename());
DateFormat dateFormatter = android.text.format.DateFormat.getMediumDateFormat(context);
DateFormat timeFormatter = android.text.format.DateFormat.getTimeFormat(context);
Date date = new Date(item.getTime());
if (i == 0 && item.getFilename().startsWith(context.getString(R.string.label_parent_dir))) {
holder.type.setText(R.string.label_parent_directory);
} else {
holder.type.setText(String.format(context.getString(R.string.last_edit),
dateFormatter.format(date), timeFormatter.format(date)));
}
if (holder.checkbox.getVisibility() == View.VISIBLE) {
if (i == 0 && item.getFilename().startsWith(context.getString(R.string.label_parent_dir))) {
holder.checkbox.setVisibility(View.INVISIBLE);
}
if (MarkedItemList.hasItem(item.getLocation())) {
holder.checkbox.setChecked(true);
} else {
holder.checkbox.setChecked(false);
}
}
holder.checkbox.setOnCheckedChangedListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(MaterialCheckbox checkbox, boolean isChecked) {
item.setMarked(isChecked);
if (item.isMarked()) {
if (properties.selection_mode == DialogConfigs.MULTI_MODE) {
MarkedItemList.addSelectedItem(item);
} else {
MarkedItemList.addSingleFile(item);
}
} else {
MarkedItemList.removeSelectedItem(item.getLocation());
}
notifyItemChecked.notifyCheckBoxIsClicked();
}
});
return view;
}
private class ViewHolder {
ImageView type_icon;
TextView name, type;
MaterialCheckbox checkbox;
ViewHolder(View itemView) {
name = itemView.findViewById(R.id.fname);
type = itemView.findViewById(R.id.ftype);
type_icon = itemView.findViewById(R.id.image_type);
checkbox = itemView.findViewById(R.id.file_mark);
}
}
public void setNotifyItemCheckedListener(NotifyItemChecked notifyItemChecked) {
this.notifyItemChecked = notifyItemChecked;
}
}
| java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/model/DialogConfigs.java | library/src/main/java/com/developer/filepicker/model/DialogConfigs.java | package com.developer.filepicker.model;
/**
* @author akshay sunil masram
*/
public abstract class DialogConfigs {
public static final int SINGLE_MODE = 0;
public static final int MULTI_MODE = 1;
public static final int FILE_SELECT = 0;
public static final int DIR_SELECT = 1;
public static final int FILE_AND_DIR_SELECT = 2;
/* PARENT_DIRECTORY*/
private static final String DIRECTORY_SEPARATOR = "/";
private static final String STORAGE_DIR = "sdcard";
/* DEFAULT_DIR is the default mount point of the SDCARD. It is the default
* mount point.
*/
public static final String DEFAULT_DIR = DIRECTORY_SEPARATOR + STORAGE_DIR;
} | java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/model/DialogProperties.java | library/src/main/java/com/developer/filepicker/model/DialogProperties.java | package com.developer.filepicker.model;
import java.io.File;
/**
* @author akshay sunil masram
*/
public class DialogProperties {
public int selection_mode;
public int selection_type;
public File root;
public File error_dir;
public File offset;
public String[] extensions;
public boolean show_hidden_files;
public DialogProperties() {
selection_mode = DialogConfigs.SINGLE_MODE;
selection_type = DialogConfigs.FILE_SELECT;
root = new File(DialogConfigs.DEFAULT_DIR);
error_dir = new File(DialogConfigs.DEFAULT_DIR);
offset = new File(DialogConfigs.DEFAULT_DIR);
extensions = null;
show_hidden_files = false;
}
} | java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/model/FileListItem.java | library/src/main/java/com/developer/filepicker/model/FileListItem.java | package com.developer.filepicker.model;
import java.util.Locale;
/**
* @author akshay sunil masram
*/
public class FileListItem implements Comparable<FileListItem> {
private String filename,location;
private boolean directory,marked;
private long time;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public boolean isDirectory() {
return directory;
}
public void setDirectory(boolean directory) {
this.directory = directory;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public boolean isMarked() {
return marked;
}
public void setMarked(boolean marked) {
this.marked = marked;
}
@Override
public int compareTo(FileListItem fileListItem) {
if(fileListItem.isDirectory()&&isDirectory()) {
return filename.toLowerCase().compareTo(fileListItem.getFilename().toLowerCase(Locale.getDefault()));
}
else if(!fileListItem.isDirectory()&&!isDirectory()) {
return filename.toLowerCase().compareTo(fileListItem.getFilename().toLowerCase(Locale.getDefault()));
}
else if(fileListItem.isDirectory()&&!isDirectory()) {
return 1;
}
else {
return -1;
}
}
} | java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/model/MarkedItemList.java | library/src/main/java/com/developer/filepicker/model/MarkedItemList.java | package com.developer.filepicker.model;
import java.util.HashMap;
import java.util.Set;
/**
* @author akshay sunil masram
*/
public class MarkedItemList {
private static HashMap<String,FileListItem> ourInstance = new HashMap<>();
public static void addSelectedItem(FileListItem item) {
ourInstance.put(item.getLocation(),item);
}
public static void removeSelectedItem(String key) {
ourInstance.remove(key);
}
public static boolean hasItem(String key) {
return ourInstance.containsKey(key);
}
public static void clearSelectionList() {
ourInstance = new HashMap<>();
}
public static void addSingleFile(FileListItem item) {
ourInstance = new HashMap<>();
ourInstance.put(item.getLocation(),item);
}
public static String[] getSelectedPaths() {
Set<String> paths = ourInstance.keySet();
String[] strings = new String[paths.size()];
int i=0;
for(String path:paths)
{ strings[i++]=path;
}
return strings;
}
public static int getFileCount() {
return ourInstance.size();
}
}
| java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/utils/Utility.java | library/src/main/java/com/developer/filepicker/utils/Utility.java | package com.developer.filepicker.utils;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import com.developer.filepicker.model.FileListItem;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;
/**
* @author akshay sunil masram
*/
public class Utility {
public static boolean checkStorageAccessPermissions(Context context) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
String permission = "android.permission.READ_EXTERNAL_STORAGE";
int res = context.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
else {
return true;
}
}
@android.annotation.TargetApi(Build.VERSION_CODES.TIRAMISU)
public static boolean checkMediaAccessPermissions(Context context) {
String audioPermission = Manifest.permission.READ_MEDIA_AUDIO;
String imagesPermission = Manifest.permission.READ_MEDIA_IMAGES;
String videoPermission = Manifest.permission.READ_MEDIA_VIDEO;
// Check for permissions and if permissions are granted then it will return true
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// You have the permissions, you can proceed with your media file operations.
return context.checkSelfPermission(audioPermission) == PackageManager.PERMISSION_GRANTED ||
context.checkSelfPermission(imagesPermission) == PackageManager.PERMISSION_GRANTED ||
context.checkSelfPermission(videoPermission) == PackageManager.PERMISSION_GRANTED;
}
return false;
}
public static ArrayList<FileListItem>
prepareFileListEntries(ArrayList<FileListItem> internalList, File inter,
ExtensionFilter filter, boolean show_hidden_files) {
try {
for (File name : Objects.requireNonNull(inter.listFiles(filter))) {
if (name.canRead()) {
if(name.getName().startsWith(".") && !show_hidden_files) continue;
FileListItem item = new FileListItem();
item.setFilename(name.getName());
item.setDirectory(name.isDirectory());
item.setLocation(name.getAbsolutePath());
item.setTime(name.lastModified());
internalList.add(item);
}
}
Collections.sort(internalList);
}
catch (NullPointerException e) {
e.printStackTrace();
internalList=new ArrayList<>();
}
return internalList;
}
}
| java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/utils/ExtensionFilter.java | library/src/main/java/com/developer/filepicker/utils/ExtensionFilter.java | package com.developer.filepicker.utils;
import com.developer.filepicker.model.DialogConfigs;
import com.developer.filepicker.model.DialogProperties;
import java.io.File;
import java.io.FileFilter;
import java.util.Locale;
/**
* @author akshay sunil masram
*/
public class ExtensionFilter implements FileFilter {
private final String[] validExtensions;
private DialogProperties properties;
public ExtensionFilter(DialogProperties properties) {
if(properties.extensions!=null) {
this.validExtensions = properties.extensions;
}
else {
this.validExtensions = new String[]{""};
}
this.properties=properties;
}
@Override
public boolean accept(File file) {
if (file.isDirectory()&&file.canRead())
{ return true;
}
else if(properties.selection_type== DialogConfigs.DIR_SELECT) {
return false;
}
else {
String name = file.getName().toLowerCase(Locale.getDefault());
for (String ext : validExtensions) {
if (name.endsWith(ext)) {
return true;
}
}
}
return false;
}
} | java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/view/FilePickerDialog.java | library/src/main/java/com/developer/filepicker/view/FilePickerDialog.java | package com.developer.filepicker.view;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.developer.filepicker.R;
import com.developer.filepicker.controller.DialogSelectionListener;
import com.developer.filepicker.controller.adapters.FileListAdapter;
import com.developer.filepicker.model.DialogConfigs;
import com.developer.filepicker.model.DialogProperties;
import com.developer.filepicker.model.FileListItem;
import com.developer.filepicker.model.MarkedItemList;
import com.developer.filepicker.utils.ExtensionFilter;
import com.developer.filepicker.utils.Utility;
import com.developer.filepicker.widget.MaterialCheckbox;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author akshay sunil masram
*/
public class FilePickerDialog extends Dialog implements AdapterView.OnItemClickListener {
private static final String TAG = FilePickerDialog.class.getSimpleName();
private final Context context;
private Activity activity;
private ListView listView;
private TextView dname, dir_path, title;
private DialogProperties properties;
private DialogSelectionListener callbacks;
private ArrayList<FileListItem> internalList;
private ExtensionFilter filter;
private FileListAdapter mFileListAdapter;
private Button select;
private String titleStr = null;
private String positiveBtnNameStr = null;
private String negativeBtnNameStr = null;
public static final int EXTERNAL_READ_PERMISSION_GRANT = 112;
private String getFileExtension(String filePath) {
int lastDotIndex = filePath.lastIndexOf('.');
if (lastDotIndex != -1) {
return filePath.substring(lastDotIndex + 1).toLowerCase();
}
return "";
}
public FilePickerDialog(Context context) {
super(context);
this.context = context;
properties = new DialogProperties();
filter = new ExtensionFilter(properties);
internalList = new ArrayList<>();
}
@Deprecated
public FilePickerDialog(Activity activity, Context context) {
super(context);
this.activity = activity;
this.context = context;
properties = new DialogProperties();
filter = new ExtensionFilter(properties);
internalList = new ArrayList<>();
}
public FilePickerDialog(Context context, DialogProperties properties, int themeResId) {
super(context, themeResId);
this.context = context;
this.properties = properties;
filter = new ExtensionFilter(properties);
internalList = new ArrayList<>();
}
@Deprecated
public FilePickerDialog(Activity activity, Context context, DialogProperties properties, int themeResId) {
super(context, themeResId);
this.activity = activity;
this.context = context;
this.properties = properties;
filter = new ExtensionFilter(properties);
internalList = new ArrayList<>();
}
public FilePickerDialog(Context context, DialogProperties properties) {
super(context);
this.context = context;
this.properties = properties;
filter = new ExtensionFilter(properties);
internalList = new ArrayList<>();
}
@Deprecated
public FilePickerDialog(Activity activity, Context context, DialogProperties properties) {
super(context);
this.activity = activity;
this.context = context;
this.properties = properties;
filter = new ExtensionFilter(properties);
internalList = new ArrayList<>();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_main);
listView = findViewById(R.id.fileList);
select = findViewById(R.id.select);
int size = MarkedItemList.getFileCount();
if (size == 0) {
select.setEnabled(false);
int color;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
color = context.getResources().getColor(R.color.colorAccent, context.getTheme());
} else {
color = context.getResources().getColor(R.color.colorAccent);
}
select.setTextColor(Color.argb(128, Color.red(color), Color.green(color),
Color.blue(color)));
}
dname = findViewById(R.id.dname);
title = findViewById(R.id.title);
dir_path = findViewById(R.id.dir_path);
Button cancel = findViewById(R.id.cancel);
if (negativeBtnNameStr != null) {
cancel.setText(negativeBtnNameStr);
}
select.setOnClickListener(view -> {
String[] paths = MarkedItemList.getSelectedPaths();
if (callbacks != null) {
callbacks.onSelectedFilePaths(paths);
}
dismiss();
});
cancel.setOnClickListener(view -> cancel());
mFileListAdapter = new FileListAdapter(internalList, context, properties);
mFileListAdapter.setNotifyItemCheckedListener(() -> {
positiveBtnNameStr = positiveBtnNameStr == null ?
context.getResources().getString(R.string.choose_button_label) : positiveBtnNameStr;
int size1 = MarkedItemList.getFileCount();
if (size1 == 0) {
select.setEnabled(false);
int color;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
color = context.getResources().getColor(R.color.colorAccent,
context.getTheme());
} else {
color = context.getResources().getColor(R.color.colorAccent);
}
select.setTextColor(Color.argb(128, Color.red(color), Color.green(color),
Color.blue(color)));
select.setText(positiveBtnNameStr);
} else {
select.setEnabled(true);
int color;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
color = context.getResources().getColor(R.color.colorAccent,
context.getTheme());
} else {
color = context.getResources().getColor(R.color.colorAccent);
}
select.setTextColor(color);
String button_label = positiveBtnNameStr + " (" + size1 + ") ";
select.setText(button_label);
}
if (properties.selection_mode == DialogConfigs.SINGLE_MODE) {
/* If a single file has to be selected, clear the previously checked
* checkbox from the list.
*/
mFileListAdapter.notifyDataSetChanged();
}
});
listView.setAdapter(mFileListAdapter);
//Title method added in version 1.0.5
setTitle();
}
private void setTitle() {
if (title == null || dname == null) {
return;
}
if (titleStr != null) {
if (title.getVisibility() == View.INVISIBLE) {
title.setVisibility(View.VISIBLE);
}
title.setText(titleStr);
if (dname.getVisibility() == View.VISIBLE) {
dname.setVisibility(View.INVISIBLE);
}
} else {
if (title.getVisibility() == View.VISIBLE) {
title.setVisibility(View.INVISIBLE);
}
if (dname.getVisibility() == View.INVISIBLE) {
dname.setVisibility(View.VISIBLE);
}
}
}
@Override
protected void onStart() {
super.onStart();
positiveBtnNameStr = (
positiveBtnNameStr == null ?
context.getResources().getString(R.string.choose_button_label) :
positiveBtnNameStr
);
select.setText(positiveBtnNameStr);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (Utility.checkMediaAccessPermissions(context)) {
//Permission granted...
Log.d(TAG, "Permission granted");
dir();
} else {
//Permissions are not granted...
Log.d(TAG, "Permissions are not granted. You need to ask permission to user before accessing the storage and showing dialog.");
}
} else {
if (Utility.checkStorageAccessPermissions(context)) {
Log.d(TAG, "Permission granted");
dir();
} else {
Log.d(TAG, "Permission not granted. You need to ask permission to user before accessing the storage and showing dialog.");
}
}
}
private void dir() {
File currLoc;
internalList.clear();
if (properties.offset.isDirectory() && validateOffsetPath()) {
currLoc = new File(properties.offset.getAbsolutePath());
FileListItem parent = new FileListItem();
parent.setFilename(context.getString(R.string.label_parent_dir));
parent.setDirectory(true);
parent.setLocation(Objects.requireNonNull(currLoc.getParentFile())
.getAbsolutePath());
parent.setTime(currLoc.lastModified());
internalList.add(parent);
} else if (properties.root.exists() && properties.root.isDirectory()) {
currLoc = new File(properties.root.getAbsolutePath());
} else {
currLoc = new File(properties.error_dir.getAbsolutePath());
}
dname.setText(currLoc.getName());
dir_path.setText(currLoc.getAbsolutePath());
setTitle();
internalList = Utility.prepareFileListEntries(internalList, currLoc, filter,
properties.show_hidden_files);
mFileListAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(this);
}
private boolean validateOffsetPath() {
String offset_path = properties.offset.getAbsolutePath();
String root_path = properties.root.getAbsolutePath();
return !offset_path.equals(root_path) && offset_path.contains(root_path);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (internalList.size() > i) {
FileListItem fitem = internalList.get(i);
if (fitem.isDirectory()) {
if (new File(fitem.getLocation()).canRead()) {
File currLoc = new File(fitem.getLocation());
dname.setText(currLoc.getName());
setTitle();
dir_path.setText(currLoc.getAbsolutePath());
internalList.clear();
if (!currLoc.getName().equals(properties.root.getName())) {
FileListItem parent = new FileListItem();
parent.setFilename(context.getString(R.string.label_parent_dir));
parent.setDirectory(true);
parent.setLocation(Objects.requireNonNull(currLoc
.getParentFile()).getAbsolutePath());
parent.setTime(currLoc.lastModified());
internalList.add(parent);
}
internalList = Utility.prepareFileListEntries(internalList, currLoc, filter,
properties.show_hidden_files);
mFileListAdapter.notifyDataSetChanged();
// Count the total number of files in the folder
countFilesInFolder(currLoc);
} else {
Toast.makeText(context, R.string.error_dir_access,
Toast.LENGTH_SHORT).show();
}
} else {
MaterialCheckbox fmark = view.findViewById(R.id.file_mark);
fmark.performClick();
}
}
}
public int countFilesInFolder(File folder) {
int count = 0;
if (folder != null && folder.isDirectory()) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
count++;
}
}
}
}
return count;
}
public DialogProperties getProperties() {
return properties;
}
public void setProperties(DialogProperties properties) {
this.properties = properties;
filter = new ExtensionFilter(properties);
}
public void setDialogSelectionListener(DialogSelectionListener callbacks) {
this.callbacks = callbacks;
}
@Override
public void setTitle(CharSequence titleStr) {
if (titleStr != null) {
this.titleStr = titleStr.toString();
} else {
this.titleStr = null;
}
setTitle();
}
public void setPositiveBtnName(CharSequence positiveBtnNameStr) {
if (positiveBtnNameStr != null) {
this.positiveBtnNameStr = positiveBtnNameStr.toString();
} else {
this.positiveBtnNameStr = null;
}
}
public void setNegativeBtnName(CharSequence negativeBtnNameStr) {
if (negativeBtnNameStr != null) {
this.negativeBtnNameStr = negativeBtnNameStr.toString();
} else {
this.negativeBtnNameStr = null;
}
}
public void markFiles(List<String> paths) {
if (paths != null && paths.size() > 0) {
if (properties.selection_mode == DialogConfigs.SINGLE_MODE) {
File temp = new File(paths.get(0));
switch (properties.selection_type) {
case DialogConfigs.DIR_SELECT:
if (temp.exists() && temp.isDirectory()) {
FileListItem item = new FileListItem();
item.setFilename(temp.getName());
item.setDirectory(temp.isDirectory());
item.setMarked(true);
item.setTime(temp.lastModified());
item.setLocation(temp.getAbsolutePath());
MarkedItemList.addSelectedItem(item);
}
break;
case DialogConfigs.FILE_SELECT:
if (temp.exists() && temp.isFile()) {
FileListItem item = new FileListItem();
item.setFilename(temp.getName());
item.setDirectory(temp.isDirectory());
item.setMarked(true);
item.setTime(temp.lastModified());
item.setLocation(temp.getAbsolutePath());
MarkedItemList.addSelectedItem(item);
}
break;
case DialogConfigs.FILE_AND_DIR_SELECT:
if (temp.exists()) {
FileListItem item = new FileListItem();
item.setFilename(temp.getName());
item.setDirectory(temp.isDirectory());
item.setMarked(true);
item.setTime(temp.lastModified());
item.setLocation(temp.getAbsolutePath());
MarkedItemList.addSelectedItem(item);
}
break;
}
} else {
for (String path : paths) {
switch (properties.selection_type) {
case DialogConfigs.DIR_SELECT:
File temp = new File(path);
if (temp.exists() && temp.isDirectory()) {
FileListItem item = new FileListItem();
item.setFilename(temp.getName());
item.setDirectory(temp.isDirectory());
item.setMarked(true);
item.setTime(temp.lastModified());
item.setLocation(temp.getAbsolutePath());
MarkedItemList.addSelectedItem(item);
}
break;
case DialogConfigs.FILE_SELECT:
temp = new File(path);
if (temp.exists() && temp.isFile()) {
FileListItem item = new FileListItem();
item.setFilename(temp.getName());
item.setDirectory(temp.isDirectory());
item.setMarked(true);
item.setTime(temp.lastModified());
item.setLocation(temp.getAbsolutePath());
MarkedItemList.addSelectedItem(item);
}
break;
case DialogConfigs.FILE_AND_DIR_SELECT:
temp = new File(path);
if (temp.exists() && (temp.isFile() || temp.isDirectory())) {
FileListItem item = new FileListItem();
item.setFilename(temp.getName());
item.setDirectory(temp.isDirectory());
item.setMarked(true);
item.setTime(temp.lastModified());
item.setLocation(temp.getAbsolutePath());
MarkedItemList.addSelectedItem(item);
}
break;
}
}
}
}
}
@Override
public void show() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (Utility.checkMediaAccessPermissions(context)) {
//Permission granted...
super.show();
positiveBtnNameStr = positiveBtnNameStr == null ?
context.getResources().getString(R.string.choose_button_label) : positiveBtnNameStr;
select.setText(positiveBtnNameStr);
int size = MarkedItemList.getFileCount();
if (size == 0) {
select.setText(positiveBtnNameStr);
} else {
String button_label = positiveBtnNameStr + " (" + size + ") ";
select.setText(button_label);
}
} else {
//Permissions are not granted...
Log.d(TAG, "Permissions are not granted");
}
} else {
if (!Utility.checkStorageAccessPermissions(context)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
((Activity) context).requestPermissions(new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE}, EXTERNAL_READ_PERMISSION_GRANT);
}
} else {
super.show();
positiveBtnNameStr = positiveBtnNameStr == null ?
context.getResources().getString(R.string.choose_button_label) : positiveBtnNameStr;
select.setText(positiveBtnNameStr);
int size = MarkedItemList.getFileCount();
if (size == 0) {
select.setText(positiveBtnNameStr);
} else {
String button_label = positiveBtnNameStr + " (" + size + ") ";
select.setText(button_label);
}
}
}
}
@Override
public void onBackPressed() {
//currentDirName is dependent on dname
String currentDirName = dname.getText().toString();
if (internalList.size() > 0) {
FileListItem fitem = internalList.get(0);
File currLoc = new File(fitem.getLocation());
if (currentDirName.equals(properties.root.getName()) ||
!currLoc.canRead()) {
super.onBackPressed();
} else {
dname.setText(currLoc.getName());
dir_path.setText(currLoc.getAbsolutePath());
internalList.clear();
if (!currLoc.getName().equals(properties.root.getName())) {
FileListItem parent = new FileListItem();
parent.setFilename(context.getString(R.string.label_parent_dir));
parent.setDirectory(true);
parent.setLocation(Objects.requireNonNull(currLoc.getParentFile())
.getAbsolutePath());
parent.setTime(currLoc.lastModified());
internalList.add(parent);
}
internalList = Utility.prepareFileListEntries(internalList, currLoc, filter,
properties.show_hidden_files);
mFileListAdapter.notifyDataSetChanged();
}
setTitle();
} else {
super.onBackPressed();
}
}
@Override
public void dismiss() {
MarkedItemList.clearSelectionList();
internalList.clear();
super.dismiss();
}
}
| java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/widget/MaterialCheckbox.java | library/src/main/java/com/developer/filepicker/widget/MaterialCheckbox.java | package com.developer.filepicker.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import com.developer.filepicker.R;
/**
* @author akshay sunil masram
*/
public class MaterialCheckbox extends View {
private Context context;
private int minDim;
private Paint paint;
private RectF bounds;
private boolean checked;
private OnCheckedChangeListener onCheckedChangeListener;
private Path tick;
public MaterialCheckbox(Context context) {
super(context);
initView(context);
}
public MaterialCheckbox(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public MaterialCheckbox(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
public void initView(Context context) {
this.context = context;
checked = false;
tick = new Path();
paint = new Paint();
bounds = new RectF();
OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
setChecked(!checked);
onCheckedChangeListener.onCheckedChanged(MaterialCheckbox.this, isChecked());
}
};
setOnClickListener(onClickListener);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isChecked()) {
paint.reset();
paint.setAntiAlias(true);
bounds.set(minDim / 10, minDim / 10, minDim - (minDim / 10), minDim - (minDim / 10));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
paint.setColor(getResources().getColor(R.color.colorAccent, context.getTheme()));
} else {
paint.setColor(getResources().getColor(R.color.colorAccent));
}
canvas.drawRoundRect(bounds, minDim / 8, minDim / 8, paint);
paint.setColor(Color.parseColor("#FFFFFF"));
paint.setStrokeWidth(minDim / 10);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.BEVEL);
canvas.drawPath(tick, paint);
} else {
paint.reset();
paint.setAntiAlias(true);
bounds.set(minDim / 10, minDim / 10, minDim - (minDim / 10), minDim - (minDim / 10));
paint.setColor(Color.parseColor("#C1C1C1"));
canvas.drawRoundRect(bounds, minDim / 8, minDim / 8, paint);
bounds.set(minDim / 5, minDim / 5, minDim - (minDim / 5), minDim - (minDim / 5));
paint.setColor(Color.parseColor("#FFFFFF"));
canvas.drawRect(bounds, paint);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = getMeasuredHeight();
int width = getMeasuredWidth();
minDim = Math.min(width, height);
bounds.set(minDim / 10, minDim / 10, minDim - (minDim / 10), minDim - (minDim / 10));
tick.moveTo(minDim / 4, minDim / 2);
tick.lineTo(minDim / 2.5f, minDim - (minDim / 3));
tick.moveTo(minDim / 2.75f, minDim - (minDim / 3.25f));
tick.lineTo(minDim - (minDim / 4), minDim / 3);
setMeasuredDimension(width, height);
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
invalidate();
}
public void setOnCheckedChangedListener(OnCheckedChangeListener onCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener;
}
}
| java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/library/src/main/java/com/developer/filepicker/widget/OnCheckedChangeListener.java | library/src/main/java/com/developer/filepicker/widget/OnCheckedChangeListener.java | package com.developer.filepicker.widget;
/**
* @author akshay sunil masram
*/
public interface OnCheckedChangeListener {
void onCheckedChanged(MaterialCheckbox checkbox, boolean isChecked);
} | java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/sample/src/main/java/com/developer/filepicker/file/MainActivity.java | sample/src/main/java/com/developer/filepicker/file/MainActivity.java | package com.developer.filepicker.file;
import static android.provider.Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.developer.filepicker.model.DialogConfigs;
import com.developer.filepicker.model.DialogProperties;
import com.developer.filepicker.view.FilePickerDialog;
import java.io.File;
import java.util.ArrayList;
//This is just sample activity for demo purposes always use the best practice to ask for
//storage permissions on Android version 6.0 and above.
public class MainActivity extends AppCompatActivity {
private FilePickerDialog filePickerDialog;
private ArrayList<ListItem> listItem;
private FileListAdapter mFileListAdapter;
private static final int REQUEST_STORAGE_PERMISSIONS = 123;
private final String readPermission = android.Manifest.permission.READ_EXTERNAL_STORAGE;
private final String writePermission = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
private static final int REQUEST_MEDIA_PERMISSIONS = 456;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize Views
RecyclerView fileList = findViewById(R.id.listView);
RadioGroup modeRadio = findViewById(R.id.modeRadio);
RadioGroup typeRadio = findViewById(R.id.typeRadio);
EditText extension = findViewById(R.id.extensions);
EditText root = findViewById(R.id.root);
EditText offset = findViewById(R.id.offset);
CheckBox show_hidden_files = findViewById(R.id.show_hidden_files);
Button apply = findViewById(R.id.apply);
Button showDialog = findViewById(R.id.show_dialog);
listItem = new ArrayList<>();
mFileListAdapter = new FileListAdapter(listItem, MainActivity.this);
fileList.setAdapter(mFileListAdapter);
fileList.setLayoutManager(new LinearLayoutManager(MainActivity.this));
fileList.setNestedScrollingEnabled(false);
//Create a DialogProperties object.
final DialogProperties properties = new DialogProperties();
//If you want to view files with specific extensions you can just call properties.extensions
// properties.extensions = new String[]{"zip","jpg","mp3","csv"};
//Instantiate FilePickerDialog with Context and DialogProperties.
filePickerDialog = new FilePickerDialog(MainActivity.this, properties);
filePickerDialog.setTitle("Select a File");
filePickerDialog.setPositiveBtnName("Select");
filePickerDialog.setNegativeBtnName("Cancel");
modeRadio.check(R.id.singleRadio);
modeRadio.setOnCheckedChangeListener((group, checkedId) -> {
if (checkedId == R.id.singleRadio) {
//Setting selection mode to single selection.
properties.selection_mode = DialogConfigs.SINGLE_MODE;
}
if (checkedId == R.id.multiRadio) {
//Setting selection mode to multiple selection.
properties.selection_mode = DialogConfigs.MULTI_MODE;
}
});
typeRadio.check(R.id.selFile);
typeRadio.setOnCheckedChangeListener((group, checkedId) -> {
if (checkedId == R.id.selFile) {
//Setting selection type to files.
properties.selection_type = DialogConfigs.FILE_SELECT;
}
if (checkedId == R.id.selDir) {
//Setting selection type to directories.
properties.selection_type = DialogConfigs.DIR_SELECT;
}
if (checkedId == R.id.selfilenddir) {
//Setting selection type to files and directories.
properties.selection_type = DialogConfigs.FILE_AND_DIR_SELECT;
}
});
apply.setOnClickListener(view -> {
String f_extension = extension.getText().toString();
if (f_extension.length() > 0) {
//Add extensions to be sorted from the EditText input to the array of String.
int commas = countCommas(f_extension);
//Array representing extensions.
String[] extensions = new String[commas + 1];
StringBuilder stringBuffer = new StringBuilder();
int i = 0;
for (int j = 0; j < f_extension.length(); j++) {
if (f_extension.charAt(j) == ',') {
extensions[i] = stringBuffer.toString();
stringBuffer = new StringBuilder();
i++;
} else {
stringBuffer.append(f_extension.charAt(j));
}
}
extensions[i] = stringBuffer.toString();
//Set String Array of extensions.
properties.extensions = extensions;
} else { //If EditText is empty, Initialise with null reference.
properties.extensions = null;
}
String foffset = root.getText().toString();
if (foffset.length() > 0 || !foffset.equals("")) {
//Setting Parent Directory.
properties.root = new File(foffset);
} else {
//Setting Parent Directory to Default SDCARD.
properties.root = new File(DialogConfigs.DEFAULT_DIR);
}
String fset = offset.getText().toString();
if (fset.length() > 0 || !fset.equals("")) {
//Setting Offset Directory.
properties.offset = new File(fset);
} else {
//Setting Parent Directory to Default SDCARD.
properties.offset = new File(DialogConfigs.DEFAULT_DIR);
}
properties.show_hidden_files = show_hidden_files.isChecked();
//Setting Alternative Directory, in case root is not accessible.This will be
//used.
properties.error_dir = new File("/mnt");
//Set new properties of dialog.
filePickerDialog.setProperties(properties);
});
showDialog.setOnClickListener(view -> {
//If Android version is 13 and greater then you can only access Audio, Images and Videos file
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//As the device is Android 13 and above so I want the permission of accessing Audio, Images, Videos
//You can ask permission according to your requirements what you want to access.
String audioPermission = android.Manifest.permission.READ_MEDIA_AUDIO;
String imagesPermission = android.Manifest.permission.READ_MEDIA_IMAGES;
String videoPermission = android.Manifest.permission.READ_MEDIA_VIDEO;
// Check for permissions and request them if needed
if (ContextCompat.checkSelfPermission(MainActivity.this, audioPermission) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(MainActivity.this, imagesPermission) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(MainActivity.this, videoPermission) == PackageManager.PERMISSION_GRANTED) {
// You have the permissions, you can proceed with your media file operations.
//Showing dialog when Show Dialog button is clicked.
filePickerDialog.show();
} else {
// You don't have the permissions. Request them.
ActivityCompat.requestPermissions(MainActivity.this, new String[]{audioPermission, imagesPermission, videoPermission}, REQUEST_MEDIA_PERMISSIONS);
}
} else {
//Android version is below 13 so we are asking normal read and write storage permissions
// Check for permissions and request them if needed
if (ContextCompat.checkSelfPermission(MainActivity.this, readPermission) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(MainActivity.this, writePermission) == PackageManager.PERMISSION_GRANTED) {
// You have the permissions, you can proceed with your file operations.
// Show the file picker dialog when needed
filePickerDialog.show();
} else {
// You don't have the permissions. Request them.
ActivityCompat.requestPermissions(MainActivity.this, new String[]{readPermission, writePermission}, REQUEST_STORAGE_PERMISSIONS);
}
}
});
//Method handle selected files.
filePickerDialog.setDialogSelectionListener(files -> {
//files is the array of paths selected by the App User.
int size = listItem.size();
listItem.clear();
mFileListAdapter.notifyItemRangeRemoved(0, size);
for (String path : files) {
File file = new File(path);
ListItem item = new ListItem();
item.setName(file.getName());
item.setPath(file.getAbsolutePath());
listItem.add(item);
}
mFileListAdapter.notifyItemRangeInserted(0, listItem.size());
});
}
private int countCommas(String f_extension) {
int count = 0;
for (char ch : f_extension.toCharArray()) {
if (ch == ',') count++;
}
return count;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_STORAGE_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permissions were granted. You can proceed with your file operations.
//Showing dialog when Show Dialog button is clicked.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
accessAllFilesPermissionDialog();
} else {
filePickerDialog.show();
}
} else {
// Permissions were denied. Show a rationale dialog or inform the user about the importance of these permissions.
showRationaleDialog();
}
}
//This conditions only works on Android 13 and above versions
if (requestCode == REQUEST_MEDIA_PERMISSIONS) {
if (grantResults.length > 0 && areAllPermissionsGranted(grantResults)) {
// Permissions were granted. You can proceed with your media file operations.
//Showing dialog when Show Dialog button is clicked.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
accessAllFilesPermissionDialog();
}
} else {
// Permissions were denied. Show a rationale dialog or inform the user about the importance of these permissions.
showRationaleDialog();
}
}
}
private boolean areAllPermissionsGranted(int[] grantResults) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
private void showRationaleDialog() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, readPermission) ||
ActivityCompat.shouldShowRequestPermissionRationale(this, writePermission)) {
// Show a rationale dialog explaining why the permissions are necessary.
new AlertDialog.Builder(this)
.setTitle("Permission Needed")
.setMessage("This app needs storage permissions to read and write files.")
.setPositiveButton("OK", (dialog, which) -> {
// Request permissions when the user clicks OK.
ActivityCompat.requestPermissions(MainActivity.this, new String[]{readPermission, writePermission}, REQUEST_STORAGE_PERMISSIONS);
})
.setNegativeButton("Cancel", (dialog, which) -> {
dialog.dismiss();
// Handle the case where the user cancels the permission request.
})
.show();
} else {
// Request permissions directly if no rationale is needed.
ActivityCompat.requestPermissions(this, new String[]{readPermission, writePermission}, REQUEST_STORAGE_PERMISSIONS);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.settings) {
Toast.makeText(MainActivity.this, "TODO Add your own action!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
private final static int APP_STORAGE_ACCESS_REQUEST_CODE = 501; // Any value
@RequiresApi(api = Build.VERSION_CODES.R)
private void accessAllFilesPermissionDialog() {
new AlertDialog.Builder(this)
.setTitle("Permission Needed")
.setMessage("This app needs all files access permissions to view files from your storage. Clicking on OK will redirect you to new window were you have to enable the option.")
.setPositiveButton("OK", (dialog, which) -> {
// Request permissions when the user clicks OK.
Intent intent = new Intent(ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + BuildConfig.APPLICATION_ID));
startActivityForResult(intent, APP_STORAGE_ACCESS_REQUEST_CODE);
})
.setNegativeButton("Cancel", (dialog, which) -> {
dialog.dismiss();
// Handle the case where the user cancels the permission request.
filePickerDialog.show();
})
.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == APP_STORAGE_ACCESS_REQUEST_CODE) {
// Permission granted. Now resume your workflow.
filePickerDialog.show();
}
}
} | java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/sample/src/main/java/com/developer/filepicker/file/FileListAdapter.java | sample/src/main/java/com/developer/filepicker/file/FileListAdapter.java | package com.developer.filepicker.file;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
class FileListAdapter extends RecyclerView.Adapter<FileListAdapter.FileListViewHolder> {
private final ArrayList<ListItem> listItems;
private final Context context;
FileListAdapter(ArrayList<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
@NonNull
@Override
public FileListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.file_list_item,
parent, false);
return new FileListViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull FileListViewHolder holder, int position) {
holder.name.setText(listItems.get(position).getName());
holder.path.setText(listItems.get(position).getPath());
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public int getItemCount() {
return listItems.size();
}
class FileListViewHolder extends RecyclerView.ViewHolder {
private final TextView name;
private final TextView path;
FileListViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
path = itemView.findViewById(R.id.path);
}
}
} | java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/sample/src/main/java/com/developer/filepicker/file/FilePickerApplication.java | sample/src/main/java/com/developer/filepicker/file/FilePickerApplication.java | package com.developer.filepicker.file;
import android.app.Application;
public class FilePickerApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
}
} | java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
TutorialsAndroid/FilePicker | https://github.com/TutorialsAndroid/FilePicker/blob/fadbd3441be89efb546e224e55a2ca8ea1dacceb/sample/src/main/java/com/developer/filepicker/file/ListItem.java | sample/src/main/java/com/developer/filepicker/file/ListItem.java | package com.developer.filepicker.file;
public class ListItem {
private String name, path;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
} | java | Apache-2.0 | fadbd3441be89efb546e224e55a2ca8ea1dacceb | 2026-01-05T02:37:36.484145Z | false |
danialgoodwin/android-widget-keyboardless-edittext | https://github.com/danialgoodwin/android-widget-keyboardless-edittext/blob/fced42a9d3109d81955afdf7af6d6b2f90cf2d40/KeyboardlessEditText2.java | KeyboardlessEditText2.java | /*
The MIT License (MIT)
Copyright (c) 2014 Danial Goodwin (danialgoodwin.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package net.simplyadvanced.widgets;
import android.content.Context;
import android.graphics.Rect;
import android.text.InputType;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* This is the same as a native EditText, except that no soft keyboard
* will appear when user clicks on widget. All other normal operations
* still work.
*
* To use in XML, add a widget for <my.package.name>.KeyboardlessEditText
* To use in Java, use one of the three constructors in this class
*/
public class KeyboardlessEditText2 extends EditText {
private static final Method mShowSoftInputOnFocus = getMethod(
EditText.class, "setShowSoftInputOnFocus", boolean.class);
private OnClickListener mOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
setCursorVisible(true);
}
};
private OnLongClickListener mOnLongClickListener = new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
setCursorVisible(true);
return false;
}
};
public KeyboardlessEditText2(Context context) {
super(context);
initialize();
}
public KeyboardlessEditText2(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public KeyboardlessEditText2(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
private void initialize() {
synchronized (this) {
setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
setFocusableInTouchMode(true);
}
// Needed to show cursor when user interacts with EditText so that the edit operations
// still work. Without the cursor, the edit operations won't appear.
setOnClickListener(mOnClickListener);
setOnLongClickListener(mOnLongClickListener);
// setShowSoftInputOnFocus(false); // This is a hidden method in TextView.
reflexSetShowSoftInputOnFocus(false); // Workaround.
// Ensure that cursor is at the end of the input box when initialized. Without this, the
// cursor may be at index 0 when there is text added via layout XML.
setSelection(getText().length());
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
hideKeyboard();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final boolean ret = super.onTouchEvent(event);
// Must be done after super.onTouchEvent()
hideKeyboard();
return ret;
}
private void hideKeyboard() {
final InputMethodManager imm = ((InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE));
if (imm != null && imm.isActive(this)) {
imm.hideSoftInputFromWindow(getApplicationWindowToken(), 0);
}
}
private void reflexSetShowSoftInputOnFocus(boolean show) {
if (mShowSoftInputOnFocus != null) {
invokeMethod(mShowSoftInputOnFocus, this, show);
} else {
// Use fallback method. Not tested.
hideKeyboard();
}
}
/**
* Returns method if available in class or superclass (recursively),
* otherwise returns null.
*/
public static Method getMethod(Class<?> cls, String methodName, Class<?>... parametersType) {
Class<?> sCls = cls.getSuperclass();
while (sCls != Object.class) {
try {
return sCls.getDeclaredMethod(methodName, parametersType);
} catch (NoSuchMethodException e) {
// Just super it again
}
sCls = sCls.getSuperclass();
}
return null;
// throw new RuntimeException("Method not found " + methodName);
}
/** Returns results if available, otherwise returns null. */
public static Object invokeMethod(Method method, Object receiver, Object... args) {
try {
return method.invoke(receiver, args);
} catch (IllegalArgumentException e) {
Log.e("Safe invoke fail", "Invalid args", e);
} catch (IllegalAccessException e) {
Log.e("Safe invoke fail", "Invalid access", e);
} catch (InvocationTargetException e) {
Log.e("Safe invoke fail", "Invalid target", e);
}
return null;
}
}
| java | MIT | fced42a9d3109d81955afdf7af6d6b2f90cf2d40 | 2026-01-05T02:37:36.029735Z | false |
danialgoodwin/android-widget-keyboardless-edittext | https://github.com/danialgoodwin/android-widget-keyboardless-edittext/blob/fced42a9d3109d81955afdf7af6d6b2f90cf2d40/ExampleKeyboardlessEditTextApp/app/src/main/java/net/simplyadvanced/examplekeyboardlessedittext/app/MainActivity.java | ExampleKeyboardlessEditTextApp/app/src/main/java/net/simplyadvanced/examplekeyboardlessedittext/app/MainActivity.java | package net.simplyadvanced.examplekeyboardlessedittext.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import net.simplyadvanced.widgets.KeyboardlessEditText;
/** Simple sample app to demonstrate the KeyboardlessEditText */
public class MainActivity extends Activity implements View.OnClickListener {
private EditText mEditText;
private View mDot;
private View mDash;
private View mBackspace;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (EditText) findViewById(R.id.inputText);
mDot = findViewById(R.id.dotButton);
mDash = findViewById(R.id.dashButton);
mBackspace = findViewById(R.id.backspaceButton);
mDot.setOnClickListener(this);
mDash.setOnClickListener(this);
mBackspace.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dotButton:
pressKey(KeyEvent.KEYCODE_PERIOD);
return;
case R.id.dashButton:
pressKey(KeyEvent.KEYCODE_MINUS);
return;
case R.id.backspaceButton:
pressKey(KeyEvent.KEYCODE_DEL);
return;
}
}
private void pressKey(int keycode) {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keycode);
mEditText.onKeyDown(keycode, event);
}
}
| java | MIT | fced42a9d3109d81955afdf7af6d6b2f90cf2d40 | 2026-01-05T02:37:36.029735Z | false |
danialgoodwin/android-widget-keyboardless-edittext | https://github.com/danialgoodwin/android-widget-keyboardless-edittext/blob/fced42a9d3109d81955afdf7af6d6b2f90cf2d40/ExampleKeyboardlessEditTextApp/app/src/main/java/net/simplyadvanced/utils/ReflectionUtils.java | ExampleKeyboardlessEditTextApp/app/src/main/java/net/simplyadvanced/utils/ReflectionUtils.java | package net.simplyadvanced.utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.util.Log;
/** Static helper methods for using reflection. This was inspired from:
* https://code.google.com/p/csipsimple/source/browse/trunk/ActionBarSherlock/src/com/actionbarsherlock/internal/utils/UtilityWrapper.java?r=1741
*/
public class ReflectionUtils {
private ReflectionUtils() {}
/**
* Returns method if available in class or superclass (recursively),
* otherwise returns null.
*/
public static Method getMethod(Class<?> cls, String methodName, Class<?>... parametersType) {
Class<?> sCls = cls.getSuperclass();
while (sCls != Object.class) {
try {
return sCls.getDeclaredMethod(methodName, parametersType);
} catch (NoSuchMethodException e) {
// Just super it again
}
sCls = sCls.getSuperclass();
}
return null;
// throw new RuntimeException("Method not found " + methodName);
}
/** Returns results if available, otherwise returns null. */
public static Object invokeMethod(Method method, Object receiver, Object... args) {
try {
return method.invoke(receiver, args);
} catch (IllegalArgumentException e) {
Log.e("Safe invoke fail", "Invalid args", e);
} catch (IllegalAccessException e) {
Log.e("Safe invoke fail", "Invalid access", e);
} catch (InvocationTargetException e) {
Log.e("Safe invoke fail", "Invalid target", e);
}
return null;
}
}
| java | MIT | fced42a9d3109d81955afdf7af6d6b2f90cf2d40 | 2026-01-05T02:37:36.029735Z | false |
danialgoodwin/android-widget-keyboardless-edittext | https://github.com/danialgoodwin/android-widget-keyboardless-edittext/blob/fced42a9d3109d81955afdf7af6d6b2f90cf2d40/ExampleKeyboardlessEditTextApp/app/src/main/java/net/simplyadvanced/widgets/KeyboardlessEditText.java | ExampleKeyboardlessEditTextApp/app/src/main/java/net/simplyadvanced/widgets/KeyboardlessEditText.java | /*
The MIT License (MIT)
Copyright (c) 2014 Danial Goodwin (danialgoodwin.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package net.simplyadvanced.widgets;
import java.lang.reflect.Method;
import net.simplyadvanced.utils.ReflectionUtils;
import android.content.Context;
import android.graphics.Rect;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
/**
* This is the same as a native EditText, except that no soft keyboard
* will appear when user clicks on widget. All other normal operations
* still work.
*
* To use in XML, add a widget for <my.package.name>.KeyboardlessEditText
* To use in Java, use one of the three constructors in this class
*/
public class KeyboardlessEditText extends EditText {
private static final Method mShowSoftInputOnFocus = ReflectionUtils.getMethod(
EditText.class, "setShowSoftInputOnFocus", boolean.class);
private OnClickListener mOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
setCursorVisible(true);
}
};
private OnLongClickListener mOnLongClickListener = new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
setCursorVisible(true);
return false;
}
};
public KeyboardlessEditText(Context context) {
super(context);
initialize();
}
public KeyboardlessEditText(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public KeyboardlessEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
private void initialize() {
synchronized (this) {
setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
setFocusableInTouchMode(true);
}
// Needed to show cursor when user interacts with EditText so that the edit operations
// still work. Without the cursor, the edit operations won't appear.
setOnClickListener(mOnClickListener);
setOnLongClickListener(mOnLongClickListener);
// setShowSoftInputOnFocus(false); // This is a hidden method in TextView.
reflexSetShowSoftInputOnFocus(false); // Workaround.
// Ensure that cursor is at the end of the input box when initialized. Without this, the
// cursor may be at index 0 when there is text added via layout XML.
setSelection(getText().length());
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
hideKeyboard();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final boolean ret = super.onTouchEvent(event);
// Must be done after super.onTouchEvent()
hideKeyboard();
return ret;
}
private void hideKeyboard() {
final InputMethodManager imm = ((InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE));
if (imm != null && imm.isActive(this)) {
imm.hideSoftInputFromWindow(getApplicationWindowToken(), 0);
}
}
private void reflexSetShowSoftInputOnFocus(boolean show) {
if (mShowSoftInputOnFocus != null) {
ReflectionUtils.invokeMethod(mShowSoftInputOnFocus, this, show);
} else {
// Use fallback method. Not tested.
hideKeyboard();
}
}
}
| java | MIT | fced42a9d3109d81955afdf7af6d6b2f90cf2d40 | 2026-01-05T02:37:36.029735Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/PokeDexApplication.java | PokeDex/src/main/java/me/grishka/examples/pokedex/PokeDexApplication.java | package me.grishka.examples.pokedex;
import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import me.grishka.appkit.imageloader.ImageCache;
import me.grishka.appkit.utils.NetworkUtils;
import me.grishka.appkit.utils.V;
public class PokeDexApplication extends Application{
@SuppressLint("StaticFieldLeak")
public static Context context;
@Override
public void onCreate(){
super.onCreate();
context=getApplicationContext();
V.setApplicationContext(context);
ImageCache.Parameters params=new ImageCache.Parameters();
params.diskCacheSize=100*1024*1024;
params.maxMemoryCacheSize=Integer.MAX_VALUE;
ImageCache.setParams(params);
NetworkUtils.setUserAgent("poke.dex/"+BuildConfig.VERSION_NAME);
}
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/MainActivity.java | PokeDex/src/main/java/me/grishka/examples/pokedex/MainActivity.java | package me.grishka.examples.pokedex;
import android.os.Bundle;
import androidx.annotation.Nullable;
import me.grishka.appkit.FragmentStackActivity;
import me.grishka.examples.pokedex.fragments.PokemonListFragment;
public class MainActivity extends FragmentStackActivity{
@Override
public void onCreate(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(savedInstanceState==null){
showFragment(new PokemonListFragment());
}
}
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/util/PaletteGenerationImageProcessingStep.java | PokeDex/src/main/java/me/grishka/examples/pokedex/util/PaletteGenerationImageProcessingStep.java | package me.grishka.examples.pokedex.util;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import me.grishka.appkit.imageloader.processing.ImageProcessingStep;
public class PaletteGenerationImageProcessingStep extends ImageProcessingStep{
private static final PaletteGenerationImageProcessingStep INSTANCE=new PaletteGenerationImageProcessingStep();
public static PaletteGenerationImageProcessingStep getInstance(){
return INSTANCE;
}
private PaletteGenerationImageProcessingStep(){
//no instance
}
@Override
public Drawable processDrawable(Drawable drawable){
if(drawable instanceof BitmapDrawable bd){
return new BitmapDrawableWithPalette(bd);
}
return null;
}
@Override
public String getMemoryCacheKey(){
return "palette";
}
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/util/BitmapDrawableWithPalette.java | PokeDex/src/main/java/me/grishka/examples/pokedex/util/BitmapDrawableWithPalette.java | package me.grishka.examples.pokedex.util;
import android.graphics.drawable.BitmapDrawable;
import androidx.palette.graphics.Palette;
public class BitmapDrawableWithPalette extends BitmapDrawable{
public final Palette palette;
public BitmapDrawableWithPalette(BitmapDrawable drawable){
super(drawable.getBitmap());
palette=new Palette.Builder(getBitmap()).generate();
}
public int getCardBackgroundColor(boolean darkTheme){
if(palette!=null){
Palette.Swatch swatch=darkTheme ? palette.getDarkMutedSwatch() : palette.getLightMutedSwatch();
if(swatch!=null)
return swatch.getRgb();
}
return darkTheme ? 0xff000000 : 0xffffffff;
}
public int getCardTextColor(boolean darkTheme){
if(palette!=null){
Palette.Swatch swatch=darkTheme ? palette.getDarkMutedSwatch() : palette.getLightMutedSwatch();
if(swatch!=null)
return swatch.getTitleTextColor() | 0xff000000;
}
return darkTheme ? 0xffffffff : 0xff000000;
}
public int[] getGradientColors(){
if(palette!=null){
Palette.Swatch vibrantSwatch=palette.getVibrantSwatch(), darkVibrantSwatch=palette.getDarkVibrantSwatch(), dominantSwatch=palette.getDominantSwatch();
if(vibrantSwatch!=null && darkVibrantSwatch!=null){
return new int[]{vibrantSwatch.getRgb(), darkVibrantSwatch.getRgb()};
}else if(vibrantSwatch!=null && dominantSwatch!=null){
return new int[]{vibrantSwatch.getRgb(), dominantSwatch.getRgb()};
}else if(dominantSwatch!=null){
return new int[]{dominantSwatch.getRgb(), dominantSwatch.getRgb()};
}
}
return new int[]{0xff000000, 0xff000000};
}
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/model/PokemonType.java | PokeDex/src/main/java/me/grishka/examples/pokedex/model/PokemonType.java | package me.grishka.examples.pokedex.model;
public enum PokemonType{
NORMAL,
FIRE,
WATER,
ELECTRIC,
GRASS,
ICE,
FIGHTING,
POISON,
GROUND,
FLYING,
PSYCHIC,
BUG,
ROCK,
GHOST,
DRAGON,
DARK,
STEEL,
FAIRY
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/model/ListPokemon.java | PokeDex/src/main/java/me/grishka/examples/pokedex/model/ListPokemon.java | package me.grishka.examples.pokedex.model;
import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import org.parceler.Parcel;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import me.grishka.appkit.imageloader.requests.ImageLoaderRequest;
import me.grishka.appkit.imageloader.requests.UrlImageLoaderRequest;
import me.grishka.examples.pokedex.api.AllFieldsAreRequired;
import me.grishka.examples.pokedex.api.ObjectValidationException;
import me.grishka.examples.pokedex.util.PaletteGenerationImageProcessingStep;
@Parcel
@AllFieldsAreRequired
public class ListPokemon extends BaseModel{
public String name;
public String url;
public transient int index;
public transient ImageLoaderRequest imgRequest;
public ListPokemon(){}
public ListPokemon(Cursor cursor){
name=cursor.getString(1);
url=cursor.getString(2);
}
@Override
public void postprocess() throws ObjectValidationException{
super.postprocess();
name=Arrays.stream(name.split("_"))
.map(part->{
if(part.isEmpty())
return part;
return Character.toUpperCase(part.charAt(0))+part.substring(1);
})
.collect(Collectors.joining(" "));
String[] urlParts=url.split(Pattern.quote("/"));
index=Integer.parseInt(urlParts[urlParts.length-1]);
// ARGB_8888 because we need to be able to access the pixels for the palette thing
imgRequest=new UrlImageLoaderRequest(Bitmap.Config.ARGB_8888, 0, 0, List.of(PaletteGenerationImageProcessingStep.getInstance()),
Uri.parse("https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/"+index+".png"));
}
public void toContentValues(ContentValues values){
values.put("id", index);
values.put("name", name);
values.put("url", url);
}
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/model/PokemonDetailsResponse.java | PokeDex/src/main/java/me/grishka/examples/pokedex/model/PokemonDetailsResponse.java | package me.grishka.examples.pokedex.model;
import java.util.List;
import me.grishka.examples.pokedex.api.AllFieldsAreRequired;
import me.grishka.examples.pokedex.api.ObjectValidationException;
import me.grishka.examples.pokedex.api.RequiredField;
@AllFieldsAreRequired
public class PokemonDetailsResponse extends BaseModel{
public int id;
public int weight;
public int height;
public List<Stat> stats;
public List<Type> types;
@Override
public void postprocess() throws ObjectValidationException{
super.postprocess();
for(Stat stat:stats){
stat.postprocess();
}
for(Type type:types){
type.postprocess();
}
}
public static class Stat extends BaseModel{
public int baseStat;
public int effort;
@RequiredField
public StatRef stat;
@Override
public void postprocess() throws ObjectValidationException{
super.postprocess();
stat.postprocess();
}
}
@AllFieldsAreRequired
public static class StatRef extends BaseModel{
public String name;
public String url;
}
@AllFieldsAreRequired
public static class Type extends BaseModel{
public int slot;
public TypeRef type;
@Override
public void postprocess() throws ObjectValidationException{
super.postprocess();
type.postprocess();
}
}
@AllFieldsAreRequired
public static class TypeRef extends BaseModel{
public String name;
public String url;
}
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/model/BaseModel.java | PokeDex/src/main/java/me/grishka/examples/pokedex/model/BaseModel.java | package me.grishka.examples.pokedex.model;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import me.grishka.examples.pokedex.api.AllFieldsAreRequired;
import me.grishka.examples.pokedex.api.ObjectValidationException;
import me.grishka.examples.pokedex.api.RequiredField;
public abstract class BaseModel implements Cloneable{
@CallSuper
public void postprocess() throws ObjectValidationException{
try{
boolean allRequired=getClass().isAnnotationPresent(AllFieldsAreRequired.class);
for(Field fld:getClass().getFields()){
if(!fld.getType().isPrimitive() && !Modifier.isTransient(fld.getModifiers()) && (allRequired || fld.isAnnotationPresent(RequiredField.class))){
if(fld.get(this)==null){
throw new ObjectValidationException("Required field '"+fld.getName()+"' of type "+fld.getType().getSimpleName()+" was null in "+getClass().getSimpleName());
}
}
}
}catch(IllegalAccessException ignore){}
}
@NonNull
@Override
public Object clone(){
try{
return super.clone();
}catch(CloneNotSupportedException x){
throw new RuntimeException(x);
}
}
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/model/PokemonDetails.java | PokeDex/src/main/java/me/grishka/examples/pokedex/model/PokemonDetails.java | package me.grishka.examples.pokedex.model;
import android.content.ContentValues;
import android.database.Cursor;
import java.util.EnumSet;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;
public class PokemonDetails{
public int index;
public int weight;
public int height;
public EnumSet<PokemonType> types;
public int health;
public int attack;
public int defense;
public int specialAttack;
public int specialDefense;
public int speed;
public PokemonDetails(Cursor cursor){
index=cursor.getInt(0);
weight=cursor.getInt(1);
height=cursor.getInt(2);
int typesMask=cursor.getInt(3);
types=EnumSet.noneOf(PokemonType.class);
for(PokemonType type:PokemonType.values()){
if((typesMask & (1 << type.ordinal()))!=0)
types.add(type);
}
health=cursor.getInt(4);
attack=cursor.getInt(5);
defense=cursor.getInt(6);
specialAttack=cursor.getInt(7);
specialDefense=cursor.getInt(8);
speed=cursor.getInt(9);
}
public PokemonDetails(PokemonDetailsResponse resp){
index=resp.id;
weight=resp.weight;
height=resp.height;
types=resp.types.stream()
.map(t->{
try{
return PokemonType.valueOf(t.type.name.toUpperCase(Locale.US));
}catch(IllegalArgumentException x){
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toCollection(()->EnumSet.noneOf(PokemonType.class)));
for(PokemonDetailsResponse.Stat stat:resp.stats){
int value=stat.baseStat;
switch(stat.stat.name){
case "hp" -> health=value;
case "attack" -> attack=value;
case "defense" -> defense=value;
case "special-attack" -> specialAttack=value;
case "special-defense" -> specialDefense=value;
case "speed" -> speed=value;
}
}
}
public void toContentValues(ContentValues values){
values.put("id", index);
values.put("weight", weight);
values.put("height", height);
int typesMask=0;
for(PokemonType type:types){
typesMask|=1 << type.ordinal();
}
values.put("types", typesMask);
values.put("health", health);
values.put("attack", attack);
values.put("defense", defense);
values.put("special_attack", specialAttack);
values.put("special_defense", specialDefense);
values.put("speed", speed);
}
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/model/PaginatedList.java | PokeDex/src/main/java/me/grishka/examples/pokedex/model/PaginatedList.java | package me.grishka.examples.pokedex.model;
import java.util.List;
import me.grishka.examples.pokedex.api.ObjectValidationException;
import me.grishka.examples.pokedex.api.RequiredField;
public class PaginatedList<T extends BaseModel> extends BaseModel{
@RequiredField
public List<T> results;
public String next;
public String previous;
public int count;
@Override
public void postprocess() throws ObjectValidationException{
super.postprocess();
for(T result:results){
result.postprocess();
}
}
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/api/RequiredField.java | PokeDex/src/main/java/me/grishka/examples/pokedex/api/RequiredField.java | package me.grishka.examples.pokedex.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface RequiredField{
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
grishka/poke.dex | https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/api/PokeAPIController.java | PokeDex/src/main/java/me/grishka/examples/pokedex/api/PokeAPIController.java | package me.grishka.examples.pokedex.api;
import android.util.Log;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.io.Reader;
import java.util.concurrent.TimeUnit;
import me.grishka.appkit.utils.WorkerThread;
import me.grishka.examples.pokedex.BuildConfig;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class PokeAPIController{
private static final String TAG="PokeAPIController";
public static final Gson gson=new GsonBuilder()
.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
private static WorkerThread thread=new WorkerThread("PokeAPIController");
private static OkHttpClient httpClient=new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
private static final PokeAPIController instance=new PokeAPIController();
static{
thread.start();
}
public static PokeAPIController getInstance(){
return instance;
}
public <T> void submitRequest(PokeAPIRequest<T> req){
thread.postRunnable(()->{
try{
Request hReq=new Request.Builder()
.url(req.url)
.addHeader("User-Agent", "poke.dex/"+BuildConfig.VERSION_NAME)
.build();
Call call=httpClient.newCall(hReq);
req.okhttpCall=call;
call.enqueue(new Callback(){
@Override
public void onFailure(Call call, IOException e){
req.okhttpCall=null;
req.onError(e.getMessage(), -1, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException{
req.okhttpCall=null;
if(req.canceled)
return;
T respObj;
try(ResponseBody body=response.body()){
Reader reader=body.charStream();
try{
if(req.respTypeToken!=null)
respObj=gson.fromJson(reader, req.respTypeToken.getType());
else if(req.respClass!=null)
respObj=gson.fromJson(reader, req.respClass);
else
respObj=null;
}catch(JsonIOException|JsonSyntaxException x){
if(BuildConfig.DEBUG)
Log.w(TAG, response+" error parsing or reading body", x);
req.onError(x.getLocalizedMessage(), response.code(), x);
return;
}
try{
req.validateAndPostprocessResponse(respObj, response);
}catch(IOException x){
if(BuildConfig.DEBUG)
Log.w(TAG, response+" error post-processing or validating response", x);
req.onError(x.getLocalizedMessage(), response.code(), x);
return;
}
if(BuildConfig.DEBUG)
Log.d(TAG, response+" parsed successfully: "+respObj);
req.onSuccess(respObj);
}catch(Exception x){
Log.w(TAG, "onResponse: error processing response", x);
req.onError(x.getMessage(), -1, x);
}
}
});
}catch(Throwable x){
Log.w(TAG, "Request "+req+" failed", x);
req.onError(x.getLocalizedMessage(), 0, x);
}
}, 0);
}
}
| java | Unlicense | 229c925988509b06b824079f8202c0a5001116f7 | 2026-01-05T02:37:37.848615Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.