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 |
|---|---|---|---|---|---|---|---|---|
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/TestMain.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/TestMain.java | package org.jeecg;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.util.RestUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
/**
* @Description: TODO
* @author: scott
* @date: 2022年05月10日 14:02
*/
public class TestMain {
public static void main(String[] args) {
// 请求地址
String url = "https://api3.boot.jeecg.com/sys/user/list";
// 请求 Header (用于传递Token)
HttpHeaders headers = getHeaders();
// 请求方式是 GET 代表获取数据
HttpMethod method = HttpMethod.GET;
//System.out.println("请求地址:" + url);
//System.out.println("请求方式:" + method);
// 利用 RestUtil 请求该url
ResponseEntity<JSONObject> result = RestUtil.request(url, method, headers, null, null, JSONObject.class);
if (result != null && result.getBody() != null) {
System.out.println("返回结果:" + result.getBody().toJSONString());
} else {
System.out.println("查询失败");
}
}
private static HttpHeaders getHeaders() {
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.50h-g6INOZRVnznExiawFb1U6PPjcVVA4POeYRA5a5Q";
System.out.println("请求Token:" + token);
HttpHeaders headers = new HttpHeaders();
String mediaType = MediaType.APPLICATION_JSON_VALUE;
headers.setContentType(MediaType.parseMediaType(mediaType));
headers.set("Accept", mediaType);
headers.set("X-Access-Token", token);
return headers;
}
}
| java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/system/test/MockControllerTest.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/system/test/MockControllerTest.java | package org.jeecg.modules.system.test;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.demo.mock.MockController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
/**
* 单个controller测试
* @date 2025/4/7 11:21
*/
@WebMvcTest(value = MockController.class)
public class MockControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private BaseCommonService baseCommonService;
@MockBean
private JeecgBaseConfig jeecgBaseConfig;
@Test
public void testSave() throws Exception {
mockMvc.perform(get("/mock/api/json/area"))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
| java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/system/test/SysTableWhiteCheckTest.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/system/test/SysTableWhiteCheckTest.java | package org.jeecg.modules.system.test;
import org.aspectj.lang.annotation.Before;
import org.jeecg.JeecgSystemApplication;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.config.firewall.SqlInjection.IDictTableWhiteListHandler;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @Description: 系统表白名单测试
* @Author: sunjianlei
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = JeecgSystemApplication.class)
public class SysTableWhiteCheckTest {
@Autowired
IDictTableWhiteListHandler whiteListHandler;
@Autowired
ISysBaseAPI sysBaseAPI;
@Autowired
JeecgBaseConfig jeecgBaseConfig;
@BeforeEach
public void before() {
String lowCodeMode = this.jeecgBaseConfig.getFirewall().getLowCodeMode();
System.out.println("当前 LowCode 模式为: " + lowCodeMode);
// 清空缓存,防止影响测试
whiteListHandler.clear();
}
@Test
public void testSql() {
System.out.println("=== 开始测试 SQL 方式 ===");
String[] sqlArr = new String[]{
"select username from sys_user",
"select username, CONCAT(realname, SEX) from SYS_USER",
"select username, CONCAT(realname, sex) from sys_user",
};
for (String sql : sqlArr) {
System.out.println("- 测试Sql: " + sql);
try {
sysBaseAPI.dictTableWhiteListCheckBySql(sql);
System.out.println("-- 测试通过");
} catch (Exception e) {
System.out.println("-- 测试未通过: " + e.getMessage());
}
}
System.out.println("=== 结束测试 SQL 方式 ===");
}
@Test
public void testDict() {
System.out.println("=== 开始测试 DICT 方式 ===");
String table = "sys_user";
String code = "username";
String text = "realname";
this.testDict(table, code, text);
table = "sys_user";
code = "username";
text = "CONCAT(realname, sex)";
this.testDict(table, code, text);
table = "SYS_USER";
code = "username";
text = "CONCAT(realname, SEX)";
this.testDict(table, code, text);
System.out.println("=== 结束测试 DICT 方式 ===");
}
private void testDict(String table, String code, String text) {
try {
sysBaseAPI.dictTableWhiteListCheckByDict(table, code, text);
System.out.println("- 测试通过");
} catch (Exception e) {
System.out.println("- 测试未通过: " + e.getMessage());
}
}
}
| java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/system/test/SampleTest.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/system/test/SampleTest.java | package org.jeecg.modules.system.test;
import jakarta.annotation.Resource;
import org.jeecg.JeecgSystemApplication;
import org.jeecg.modules.demo.mock.MockController;
import org.jeecg.modules.demo.test.entity.JeecgDemo;
import org.jeecg.modules.demo.test.mapper.JeecgDemoMapper;
import org.jeecg.modules.demo.test.service.IJeecgDemoService;
import org.jeecg.modules.system.service.ISysDataLogService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.Assert;
import java.util.List;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = JeecgSystemApplication.class)
public class SampleTest {
@Resource
private JeecgDemoMapper jeecgDemoMapper;
@Resource
private IJeecgDemoService jeecgDemoService;
@Resource
private ISysDataLogService sysDataLogService;
@Resource
private MockController mock;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<JeecgDemo> userList = jeecgDemoMapper.selectList(null);
Assert.isTrue(15==userList.size(),"结果不是5条");
userList.forEach(System.out::println);
}
@Test
public void testXmlSql() {
System.out.println(("----- selectAll method test ------"));
List<JeecgDemo> userList = jeecgDemoMapper.getDemoByName("Sandy12");
userList.forEach(System.out::println);
}
/**
* 测试事务
*/
@Test
public void testTran() {
jeecgDemoService.testTran();
}
/**
* 测试数据日志添加
*/
@Test
public void testDataLogSave() {
System.out.println(("----- datalog test ------"));
String tableName = "jeecg_demo";
String dataId = "4028ef81550c1a7901550c1cd6e70001";
String dataContent = mock.sysDataLogJson();
sysDataLogService.addDataLog(tableName, dataId, dataContent);
}
}
| java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/system/test/SysUserApiTest.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/system/test/SysUserApiTest.java | package org.jeecg.modules.system.test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.modules.redis.client.JeecgRedisClient;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.controller.SysUserController;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
/**
* 系统用户单元测试
*/
@WebMvcTest(SysUserController.class)
public class SysUserApiTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private ISysUserService sysUserService;
@MockBean
private ISysDepartService sysDepartService;
@MockBean
private ISysUserRoleService sysUserRoleService;
@MockBean
private ISysUserDepartService sysUserDepartService;
@MockBean
private ISysDepartRoleUserService departRoleUserService;
@MockBean
private ISysDepartRoleService departRoleService;
@MockBean
private RedisUtil redisUtil;
@Value("${jeecg.path.upload}")
private String upLoadPath;
@MockBean
private BaseCommonService baseCommonService;
@MockBean
private ISysPositionService sysPositionService;
@MockBean
private ISysUserTenantService userTenantService;
@MockBean
private JeecgRedisClient jeecgRedisClient;
@MockBean
private JeecgBaseConfig jeecgBaseConfig;
/**
* 测试地址:实际使用时替换成你自己的地址
*/
private final String BASE_URL = "/sys/user/";
/**
* 测试用例:查询记录
*/
@Test
public void testQuery() throws Exception{
// 请求地址
String url = BASE_URL + "list";
Page<SysUser> sysUserPage = new Page<>();
SysUser sysUser = new SysUser();
sysUser.setUsername("admin");
List<SysUser> users = new ArrayList<>();
users.add(sysUser);
sysUserPage.setRecords(users);
sysUserPage.setCurrent(1);
sysUserPage.setSize(10);
sysUserPage.setTotal(1);
given(this.sysUserService.queryPageList(any(), any(), any(), any())).willReturn(Result.OK(sysUserPage));
String result = mockMvc.perform(get(url)).andReturn().getResponse().getContentAsString();
JSONObject jsonObject = JSON.parseObject(result);
Assertions.assertEquals("admin", jsonObject.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("username"));
}
/**
* 测试用例:新增
*/
@Test
public void testAdd() throws Exception {
// 请求地址
String url = BASE_URL + "add" ;
JSONObject params = new JSONObject();
params.put("username", "wangwuTest");
params.put("password", "123456");
params.put("confirmpassword","123456");
params.put("realname", "单元测试");
params.put("activitiSync", "1");
params.put("userIdentity","1");
params.put("workNo","0025");
String result = mockMvc.perform(post(url).contentType(MediaType.APPLICATION_JSON_VALUE).content(params.toJSONString()))
.andReturn().getResponse().getContentAsString();
JSONObject jsonObject = JSON.parseObject(result);
Assertions.assertTrue(jsonObject.getBoolean("success"));
}
/**
* 测试用例:修改
*/
@Test
public void testEdit() throws Exception {
// 数据Id
String dataId = "1331795062924374018";
// 请求地址
String url = BASE_URL + "edit";
JSONObject params = new JSONObject();
params.put("username", "wangwuTest");
params.put("realname", "单元测试1111");
params.put("activitiSync", "1");
params.put("userIdentity","1");
params.put("workNo","0025");
params.put("id",dataId);
SysUser sysUser = new SysUser();
sysUser.setUsername("admin");
given(this.sysUserService.getById(any())).willReturn(sysUser);
String result = mockMvc.perform(put(url).contentType(MediaType.APPLICATION_JSON_VALUE).content(params.toJSONString()))
.andReturn().getResponse().getContentAsString();
JSONObject jsonObject = JSON.parseObject(result);
Assertions.assertTrue(jsonObject.getBoolean("success"));
}
/**
* 测试用例:删除
*/
@Test
public void testDelete() throws Exception {
// 数据Id
String dataId = "1331795062924374018";
// 请求地址
String url = BASE_URL + "delete" + "?id=" + dataId;
String result = mockMvc.perform(delete(url)).andReturn().getResponse().getContentAsString();
JSONObject jsonObject = JSON.parseObject(result);
Assertions.assertTrue(jsonObject.getBoolean("success"));
}
}
| java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/message/test/SendMessageTest.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/message/test/SendMessageTest.java | package org.jeecg.modules.message.test;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import org.jeecg.JeecgSystemApplication;
import org.jeecg.common.api.dto.message.BusMessageDTO;
import org.jeecg.common.api.dto.message.BusTemplateMessageDTO;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.DySmsEnum;
import org.jeecg.common.constant.enums.EmailTemplateEnum;
import org.jeecg.common.constant.enums.MessageTypeEnum;
import org.jeecg.common.constant.enums.SysAnnmentTypeEnum;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.DySmsHelper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.HashMap;
import java.util.Map;
/**
* @Description: 消息推送测试
* @Author: lsq
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = JeecgSystemApplication.class)
public class SendMessageTest {
@Autowired
ISysBaseAPI sysBaseAPI;
/**
* 发送系统消息
*/
@Test
public void sendSysAnnouncement() {
//发送人
String fromUser = "admin";
//接收人
String toUser = "jeecg";
//标题
String title = "系统消息";
//内容
String msgContent = "TEST:今日份日程计划已送达!";
//发送系统消息
sysBaseAPI.sendSysAnnouncement(new MessageDTO(fromUser, toUser, title, msgContent));
//消息类型
String msgCategory = CommonConstant.MSG_CATEGORY_1;
//业务类型
String busType = SysAnnmentTypeEnum.EMAIL.getType();
//业务ID
String busId = "11111";
//发送带业务参数的系统消息
BusMessageDTO busMessageDTO = new BusMessageDTO(fromUser, toUser, title, msgContent, msgCategory, busType,busId);
sysBaseAPI.sendBusAnnouncement(busMessageDTO);
}
/**
* 发送模版消息
*/
@Test
public void sendTemplateAnnouncement() {
//发送人
String fromUser = "admin";
//接收人
String toUser = "jeecg";
//标题
String title = "通知公告";
//模版编码
String templateCode = "412358";
//模版参数
Map templateParam = new HashMap<>();
templateParam.put("realname","JEECG用户");
sysBaseAPI.sendTemplateAnnouncement(new TemplateMessageDTO(fromUser,toUser,title,templateParam,templateCode));
//业务类型
String busType = SysAnnmentTypeEnum.EMAIL.getType();
//业务ID
String busId = "11111";
//发送带业务参数的模版消息
BusTemplateMessageDTO busMessageDTO = new BusTemplateMessageDTO(fromUser, toUser, title, templateParam ,templateCode, busType,busId);
sysBaseAPI.sendBusTemplateAnnouncement(busMessageDTO);
//新发送模版消息
MessageDTO messageDTO = new MessageDTO();
messageDTO.setType(MessageTypeEnum.XT.getType());
messageDTO.setToAll(false);
messageDTO.setToUser(toUser);
messageDTO.setTitle("【流程错误】");
messageDTO.setFromUser("admin");
HashMap data = new HashMap<>();
data.put(CommonConstant.NOTICE_MSG_BUS_TYPE, "msg_node");
messageDTO.setData(data);
messageDTO.setContent("TEST:流程执行失败!任务节点未找到");
sysBaseAPI.sendTemplateMessage(messageDTO);
}
/**
* 发送邮件
*/
@Test
public void sendEmailMsg() {
String title = "【日程提醒】您的日程任务即将开始";
String content = "TEST:尊敬的王先生,您购买的演唱会将于本周日10:08分在国家大剧院如期举行,届时请携带好您的门票和身份证到场";
String email = "250678106@qq.com";
sysBaseAPI.sendEmailMsg(email,title,content);
}
/**
* 发送html模版邮件
*/
@Test
public void sendTemplateEmailMsg() {
String title = "收到一个催办";
String email = "250678106@qq.com";
JSONObject params = new JSONObject();
params.put("bpm_name","高级设置");
params.put("bpm_task","审批人");
params.put("datetime","2023-10-07 18:00:49");
params.put("url","http://boot3.jeecg.com/message/template");
params.put("remark","快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点快点");
sysBaseAPI.sendHtmlTemplateEmail(email,title, EmailTemplateEnum.BPM_CUIBAN_EMAIL,params);
}
/**
* 发送短信
*/
@Test
public void sendSms() throws ClientException {
//手机号
String mobile = "159***";
//消息模版
DySmsEnum templateCode = DySmsEnum.LOGIN_TEMPLATE_CODE;
//模版所需参数
JSONObject obj = new JSONObject();
obj.put("code", "4XDP");
DySmsHelper.sendSms(mobile, obj, templateCode);
}
}
| java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/openapi/test/SampleOpenApiTest.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/modules/openapi/test/SampleOpenApiTest.java | package org.jeecg.modules.openapi.test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import java.security.MessageDigest;
public class SampleOpenApiTest {
private final String base_url = "http://localhost:8080/jeecg-boot";
private final String appKey = "ak-pFjyNHWRsJEFWlu6";
private final String searchKey = "4hV5dBrZtmGAtPdbA5yseaeKRYNpzGsS";
@Test
public void test() throws Exception {
// 根据部门ID查询用户
String url = base_url+"/openapi/call/TEwcXBlr?id=c6d7cb4deeac411cb3384b1b31278596";
JSONObject header = genTimestampAndSignature();
HttpGet httpGet = new HttpGet(url);
// 设置请求头
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("appkey",appKey);
httpGet.setHeader("signature",header.get("signature").toString());
httpGet.setHeader("timestamp",header.get("timestamp").toString());
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpGet);) {
// 获取响应状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("[debug] 响应状态码: " + statusCode);
HttpEntity entity = response.getEntity();
System.out.println(entity);
// 获取响应内容
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("[debug] 响应内容: " + responseBody);
// 解析JSON响应
JSONObject res = JSON.parseObject(responseBody);
//错误日志判断
if(res.containsKey("success")){
Boolean success = res.getBoolean("success");
if(success){
System.out.println("[info] 调用成功: " + res.toJSONString());
}else{
System.out.println("[error] 调用失败: " + res.getString("message"));
}
}else{
System.out.println("[error] 调用失败: " + res.getString("message"));
}
}
}
private JSONObject genTimestampAndSignature(){
JSONObject jsonObject = new JSONObject();
long timestamp = System.currentTimeMillis();
jsonObject.put("timestamp",timestamp);
jsonObject.put("signature", md5(appKey + searchKey + timestamp));
return jsonObject;
}
/**
* 生成md5
* @param sourceStr
* @return
*/
protected String md5(String sourceStr) {
String result = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(sourceStr.getBytes("utf-8"));
byte[] hash = md.digest();
int i;
StringBuffer buf = new StringBuffer(32);
for (int offset = 0; offset < hash.length; offset++) {
i = hash[offset];
if (i < 0) {
i += 256;
}
if (i < 16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
result = buf.toString();
} catch (Exception e) {
throw new RuntimeException("sign签名错误", e);
}
return result;
}
}
| java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/smallTools/TestSqlHandle.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/smallTools/TestSqlHandle.java | package org.jeecg.smallTools;
import org.junit.jupiter.api.Test;
/**
* 测试sql分割、替换等操作
*
* @author: scott
* @date: 2023年09月05日 16:13
*/
public class TestSqlHandle {
/**
* Where 分割测试
*/
@Test
public void testSqlSplitWhere() {
String tableFilterSql = " select * from data.sys_user Where name='12312' and age>100";
String[] arr = tableFilterSql.split(" (?i)where ");
for (String sql : arr) {
System.out.println("sql片段:" + sql);
}
}
/**
* Where 替换
*/
@Test
public void testSqlWhereReplace() {
String input = " Where name='12312' and age>100";
String pattern = "(?i)where "; // (?i) 表示不区分大小写
String replacedString = input.replaceAll(pattern, "");
System.out.println("替换前的字符串:" + input);
System.out.println("替换后的字符串:" + replacedString);
}
}
| java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/smallTools/TestStr.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/test/java/org/jeecg/smallTools/TestStr.java | package org.jeecg.smallTools;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.DateUtils;
import org.junit.jupiter.api.Test;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
/**
* 字符串处理测试
*
* @author: scott
* @date: 2023年03月30日 15:27
*/
public class TestStr {
/**
* 测试参数格式化的问题,数字值有问题
*/
@Test
public void testParameterFormat() {
String url = "/pages/lowApp/process/taskDetail?tenantId={0}&procInsId={1}&taskId={2}&taskDefKey={3}";
String cc = MessageFormat.format(url, "6364", "111", "22", "333");
System.out.println("参数是字符串:" + cc);
String cc2 = MessageFormat.format(url, 6364, 111, 22, 333);
System.out.println("参数是数字(出问题):" + cc2);
}
@Test
public void testStringSplitError() {
String conditionValue = "qweqwe";
String[] conditionValueArray = conditionValue.split(",");
System.out.println("length = "+ conditionValueArray.length);
Arrays.stream(conditionValueArray).forEach(System.out::println);
}
@Test
public void getThisDate() {
LocalDate d = DateUtils.getLocalDate();
System.out.println(d);
}
@Test
public void firstDayOfLastSixMonths() {
LocalDate today = LocalDate.now(); // 获取当前日期
LocalDate firstDayOfLastSixMonths = today.minusMonths(6).withDayOfMonth(1); // 获取近半年的第一天
LocalDateTime firstDateTime = LocalDateTime.of(firstDayOfLastSixMonths, LocalTime.MIN); // 设置时间为当天的最小时间(00:00:00)
Date date = Date.from(firstDateTime.atZone(ZoneId.systemDefault()).toInstant()); // 将 LocalDateTime 转换为 Date
System.out.println("近半年的第一天的 00:00:00 时间戳:" + date);
}
@Test
public void testJSONArrayJoin() {
JSONArray valArray = new JSONArray();
valArray.add("123");
valArray.add("qwe");
System.out.println("值: " + StringUtils.join(valArray, ","));
}
@Test
public void testSql() {
String sql = "select * from sys_user where sex = ${sex}";
sql = sql.replaceAll("'?\\$\\{sex}'?","1");
System.out.println(sql);
}
@Test
public void base64(){
String encodedString = "5L+d5a2Y5aSx6LSl77yM5YWN6LS554mI5pyA5aSa5Yib5bu6ezB95p2h6L+e5o6l77yM6K+35Y2H57qn5ZWG5Lia54mI77yB";
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);
String tipMsg = MessageFormat.format(decodedString, 10);
System.out.println(tipMsg);
}
/**
* 正则测试字符串只保存中文和数字和字母
*/
@Test
public void testSpecialChar() {
String str = "Hello, World! 你好!这是一段特殊符号的测试,This is__ a test string with special characters: @#$%^&*";
// 使用正则表达式替换特殊字符
String replacedStr = str.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", "");
System.out.println("Replaced String: " + replacedStr);
}
}
| java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/JeecgSystemApplication.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/JeecgSystemApplication.java | package org.jeecg;
import com.xkcoding.justauth.autoconfigure.JustAuthAutoConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
/**
* 单体启动类(采用此类启动为单体模式)
* 报错提醒: 未集成mongo报错,可以打开启动类上面的注释 exclude={MongoAutoConfiguration.class}
*/
@Slf4j
@SpringBootApplication(exclude = MongoAutoConfiguration.class)
@ImportAutoConfiguration(JustAuthAutoConfiguration.class) // spring boot 3.x justauth 兼容性处理
public class JeecgSystemApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(JeecgSystemApplication.class);
}
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(JeecgSystemApplication.class);
Map<String, Object> defaultProperties = new HashMap<>();
defaultProperties.put("management.health.elasticsearch.enabled", false);
app.setDefaultProperties(defaultProperties);
log.info("[JEECG] Elasticsearch Health Check Enabled: false" );
ConfigurableApplicationContext application = app.run(args);;
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = oConvertUtils.getString(env.getProperty("server.servlet.context-path"));
log.info("\n----------------------------------------------------------\n\t" +
"Application Jeecg-Boot is running! Access URLs:\n\t" +
"Local: \t\thttp://localhost:" + port + path + "\n\t" +
"External: \thttp://" + ip + ":" + port + path + "/doc.html\n\t" +
"Swagger文档: \thttp://" + ip + ":" + port + path + "/doc.html\n" +
"----------------------------------------------------------");
}
} | java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/codegenerate/JeecgOneGUI.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/codegenerate/JeecgOneGUI.java | package org.jeecg.codegenerate;
import org.jeecgframework.codegenerate.window.CodeWindow;
/**
* @Title: 单表代码生成器入口
* 【 GUI模式功能弱一些,请优先使用Online代码生成 】
* @Author 张代浩
* @site www.jeecg.com
* @Version:V1.0.1
*/
public class JeecgOneGUI {
/** 使用手册: https://help.jeecg.com/java/codegen/gui */
public static void main(String[] args) {
new CodeWindow().pack();
}
} | java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/codegenerate/JeecgOneToMainUtil.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/codegenerate/JeecgOneToMainUtil.java | package org.jeecg.codegenerate;
import java.util.ArrayList;
import java.util.List;
import org.jeecgframework.codegenerate.generate.impl.CodeGenerateOneToMany;
import org.jeecgframework.codegenerate.generate.pojo.onetomany.MainTableVo;
import org.jeecgframework.codegenerate.generate.pojo.onetomany.SubTableVo;
/**
* 代码生成器入口【一对多】
*
* 【 GUI模式功能弱一些,请优先使用Online代码生成 】
* @Author 张代浩
* @site www.jeecg.com
*
*/
public class JeecgOneToMainUtil {
/**
* 一对多(父子表)数据模型,生成方法
* @param args
*/
public static void main(String[] args) {
//第一步:设置主表配置
MainTableVo mainTable = new MainTableVo();
//表名
mainTable.setTableName("jeecg_order_main");
//实体名
mainTable.setEntityName("GuiTestOrderMain");
//包名
mainTable.setEntityPackage("gui");
//描述
mainTable.setFtlDescription("GUI订单管理");
//第二步:设置子表集合配置
List<SubTableVo> subTables = new ArrayList<SubTableVo>();
//[1].子表一
SubTableVo po = new SubTableVo();
//表名
po.setTableName("jeecg_order_customer");
//实体名
po.setEntityName("GuiTestOrderCustom");
//包名
po.setEntityPackage("gui");
//描述
po.setFtlDescription("客户明细");
//子表外键参数配置
/*说明:
* a) 子表引用主表主键ID作为外键,外键字段必须以_ID结尾;
* b) 主表和子表的外键字段名字,必须相同(除主键ID外);
* c) 多个外键字段,采用逗号分隔;
*/
po.setForeignKeys(new String[]{"order_id"});
subTables.add(po);
//[2].子表二
SubTableVo po2 = new SubTableVo();
//表名
po2.setTableName("jeecg_order_ticket");
//实体名
po2.setEntityName("GuiTestOrderTicket");
//包名
po2.setEntityPackage("gui");
//描述
po2.setFtlDescription("产品明细");
//子表外键参数配置
/*说明:
* a) 子表引用主表主键ID作为外键,外键字段必须以_ID结尾;
* b) 主表和子表的外键字段名字,必须相同(除主键ID外);
* c) 多个外键字段,采用逗号分隔;
*/
po2.setForeignKeys(new String[]{"order_id"});
subTables.add(po2);
mainTable.setSubTables(subTables);
//第三步:一对多(父子表)数据模型,代码生成
try {
new CodeGenerateOneToMany(mainTable,subTables).generateCodeFile(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
jeecgboot/JeecgBoot | https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/config/flyway/FlywayConfig.java | jeecg-boot/jeecg-module-system/jeecg-system-start/src/main/java/org/jeecg/config/flyway/FlywayConfig.java | package org.jeecg.config.flyway;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import javax.sql.DataSource;
import java.util.Map;
/**
* @Description: 初始化flyway配置 修改之后支持多数据源,当出现异常时打印日志,不影响项目启动
*
* @author: wangshuai
* @date: 2024/3/12 10:03
*/
@Slf4j
@Configuration
public class FlywayConfig {
@Autowired
private DataSource dataSource;
@Autowired
private Environment environment;
/**
* 是否开启flyway
*/
@Value("${spring.flyway.enabled:false}")
private Boolean enabled;
/**
* 编码格式,默认UTF-8
*/
@Value("${spring.flyway.encoding:UTF-8}")
private String encoding;
/**
* 迁移sql脚本文件存放路径,官方默认db/migration
*/
@Value("${spring.flyway.locations:classpath:flyway/sql/mysql}")
private String locations;
/**
* 迁移sql脚本文件名称的前缀,默认V
*/
@Value("${spring.flyway.sql-migration-prefix:V}")
private String sqlMigrationPrefix;
/**
* 迁移sql脚本文件名称的分隔符,默认2个下划线__
*/
@Value("${spring.flyway.sql-migration-separator:__}")
private String sqlMigrationSeparator;
/**
* 文本前缀
*/
@Value("${spring.flyway.placeholder-prefix:#(}")
private String placeholderPrefix;
/**
* 文本后缀
*/
@Value("${spring.flyway.placeholder-suffix:)}")
private String placeholderSuffix;
/**
* 迁移sql脚本文件名称的后缀
*/
@Value("${spring.flyway.sql-migration-suffixes:.sql}")
private String sqlMigrationSuffixes;
/**
* 迁移时是否进行校验,默认true
*/
@Value("${spring.flyway.validate-on-migrate:true}")
private Boolean validateOnMigrate;
/**
* 当迁移发现数据库非空且存在没有元数据的表时,自动执行基准迁移,新建schema_version表
*/
@Value("${spring.flyway.baseline-on-migrate:true}")
private Boolean baselineOnMigrate;
/**
* 是否关闭要清除已有库下的表功能,生产环境必须为true,否则会删库,非常重要!!!
*/
@Value("${spring.flyway.clean-disabled:true}")
private Boolean cleanDisabled;
@PostConstruct
public void migrate() {
if(!enabled){
return;
}
DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
Map<String, DataSource> dataSources = ds.getDataSources();
dataSources.forEach((k, v) -> {
if("master".equals(k)){
String databaseType = environment.getProperty("spring.datasource.dynamic.datasource." + k + ".url");
if (databaseType != null && databaseType.contains("mysql")) {
try {
Flyway flyway = Flyway.configure()
.dataSource(v)
.locations(locations)
.encoding(encoding)
.sqlMigrationPrefix(sqlMigrationPrefix)
.sqlMigrationSeparator(sqlMigrationSeparator)
.placeholderPrefix(placeholderPrefix)
.placeholderSuffix(placeholderSuffix)
.sqlMigrationSuffixes(sqlMigrationSuffixes)
.validateOnMigrate(validateOnMigrate)
.baselineOnMigrate(baselineOnMigrate)
.cleanDisabled(cleanDisabled)
.load();
flyway.migrate();
log.info("【数据库升级】平台集成了MySQL库的Flyway,数据库版本自动升级! ");
} catch (FlywayException e) {
log.error("【数据库升级】flyway执行sql脚本失败", e);
}
} else {
log.warn("【数据库升级】平台只集成了MySQL库的Flyway,实现了数据库版本自动升级! 其他类型的数据库,您可以考虑手工升级~");
}
}
});
}
} | java | Apache-2.0 | e533af285c68b205f4ee8cf059d34fbb21d222d3 | 2026-01-04T14:45:57.045651Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/plugin/bus-gradle-plugin/src/test/java/com/blankj/bus/BusTest.java | plugin/bus-gradle-plugin/src/test/java/com/blankj/bus/BusTest.java | package com.blankj.bus;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/09
* desc :
* </pre>
*/
public class BusTest {
private static final String TAG_NO_PARAM = "TagNoParam";
private static final String TAG_ONE_PARAM = "TagOneParam";
private static final String TAG_NO_PARAM_STICKY = "TagNoParamSticky";
private static final String TAG_ONE_PARAM_STICKY = "TagOneParamSticky";
private String[] arr = new String[]{"0", "1"};
private String[] arr2 = new String[]{"0", "1"};
@BusUtils.Bus(tag = TAG_NO_PARAM)
public void noParamFun() {
System.out.println("noParam");
}
@BusUtils.Bus(tag = TAG_NO_PARAM, priority = 1)
public void sameTagP1Fun() {
System.out.println("noParam");
}
@BusUtils.Bus(tag = TAG_NO_PARAM)
public void sameTagParam2Fun(int arg0, Object arg1) {
System.out.println("params2");
}
@BusUtils.Bus(tag = "params2")
public void param2Fun(int arg0, Object arg1) {
System.out.println("params2");
}
@BusUtils.Bus(tag = TAG_ONE_PARAM)
public void oneParamFun(String param) {
System.out.println(param);
}
@BusUtils.Bus(tag = TAG_NO_PARAM_STICKY, sticky = true)
public void noParamStickyFun() {
System.out.println("noParamSticky");
}
@BusUtils.Bus(tag = TAG_ONE_PARAM_STICKY, sticky = true)
public void oneParamStickyFun(Callback callback) {
for (String str : arr) {
System.out.println(str);
}
for (String str1 : arr2) {
System.out.println(str1);
}
if (callback != null) {
System.out.println(callback.call());
}
}
@BusUtils.Bus(tag = "manyparam", threadMode = BusUtils.ThreadMode.SINGLE)
public void haha(int a, int b) {
final Thread thread = Thread.currentThread();
System.out.println(new Callback() {
@Override
public String call() {
return thread.toString();
}
});
}
@Test
public void testInject() throws IOException {
inject2BusUtils(getBuses());
}
private static Map<String, List<BusInfo>> getBuses() throws IOException {
Map<String, List<BusInfo>> busMap = new HashMap<>();
ClassReader cr = new ClassReader(BusTest.class.getName());
ClassWriter cw = new ClassWriter(cr, 0);
ClassVisitor cv = new BusClassVisitor(cw, busMap, BusUtils.class.getName());
cr.accept(cv, ClassReader.SKIP_FRAMES);
for (List<BusInfo> value : busMap.values()) {
value.sort(new Comparator<BusInfo>() {
@Override
public int compare(BusInfo t0, BusInfo t1) {
return t1.priority - t0.priority;
}
});
}
System.out.println("busMap = " + busMap);
return busMap;
}
private static void inject2BusUtils(Map<String, List<BusInfo>> busMap) throws IOException {
ClassReader cr = new ClassReader(BusUtils.class.getName());
ClassWriter cw = new ClassWriter(cr, 0);
ClassVisitor cv = new BusUtilsClassVisitor(cw, busMap, BusUtils.class.getName());
cr.accept(cv, ClassReader.SKIP_FRAMES);
FileUtils.writeByteArrayToFile(new File("BusUtils2333.class"), cw.toByteArray());
}
public interface Callback {
String call();
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/plugin/bus-gradle-plugin/src/test/java/com/blankj/bus/BusUtils.java | plugin/bus-gradle-plugin/src/test/java/com/blankj/bus/BusUtils.java | package com.blankj.bus;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/10/02
* desc : utils about bus
* </pre>
*/
public final class BusUtils {
private static final Object NULL = "nULl";
private static final String TAG = "BusUtils";
private final Map<String, List<BusInfo>> mTag_BusInfoListMap = new HashMap<>();
private final Map<String, Set<Object>> mClassName_BusesMap = new ConcurrentHashMap<>();
private final Map<String, List<String>> mClassName_TagsMap = new HashMap<>();
private final Map<String, Map<String, Object>> mClassName_Tag_Arg4StickyMap = new ConcurrentHashMap<>();
private BusUtils() {
init();
}
/**
* It'll be injected the bus who have {@link Bus} annotation
* by function of {@link BusUtils#registerBus} when execute transform task.
*/
private void init() {/*inject*/}
private void registerBus(String tag,
String className, String funName, String paramType, String paramName,
boolean sticky, String threadMode) {
registerBus(tag, className, funName, paramType, paramName, sticky, threadMode, 0);
}
private void registerBus(String tag,
String className, String funName, String paramType, String paramName,
boolean sticky, String threadMode, int priority) {
List<BusInfo> busInfoList = mTag_BusInfoListMap.get(tag);
if (busInfoList == null) {
busInfoList = new ArrayList<>();
mTag_BusInfoListMap.put(tag, busInfoList);
}
busInfoList.add(new BusInfo(className, funName, paramType, paramName, sticky, threadMode, priority));
}
public static void register(final Object bus) {
getInstance().registerInner(bus);
}
public static void unregister(final Object bus) {
getInstance().unregisterInner(bus);
}
public static void post(final String tag) {
post(tag, NULL);
}
public static void post(final String tag, final Object arg) {
getInstance().postInner(tag, arg);
}
public static void postSticky(final String tag) {
postSticky(tag, NULL);
}
public static void postSticky(final String tag, final Object arg) {
getInstance().postStickyInner(tag, arg);
}
public static void removeSticky(final String tag) {
getInstance().removeStickyInner(tag);
}
public static String toString_() {
return getInstance().toString();
}
@Override
public String toString() {
return "BusUtils: " + mTag_BusInfoListMap;
}
private static BusUtils getInstance() {
return LazyHolder.INSTANCE;
}
private void registerInner(final Object bus) {
if (bus == null) return;
Class aClass = bus.getClass();
String className = aClass.getName();
synchronized (mClassName_BusesMap) {
Set<Object> buses = mClassName_BusesMap.get(className);
if (buses == null) {
buses = new CopyOnWriteArraySet<>();
mClassName_BusesMap.put(className, buses);
}
buses.add(bus);
}
List<String> tags = mClassName_TagsMap.get(className);
if (tags == null) {
synchronized (mClassName_TagsMap) {
tags = mClassName_TagsMap.get(className);
if (tags == null) {
tags = new ArrayList<>();
for (Map.Entry<String, List<BusInfo>> entry : mTag_BusInfoListMap.entrySet()) {
for (BusInfo busInfo : entry.getValue()) {
try {
if (Class.forName(busInfo.className).isAssignableFrom(aClass)) {
tags.add(entry.getKey());
busInfo.classNames.add(className);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
mClassName_TagsMap.put(className, tags);
}
}
}
processSticky(bus);
}
private void processSticky(final Object bus) {
Map<String, Object> tagArgMap = mClassName_Tag_Arg4StickyMap.get(bus.getClass().getName());
if (tagArgMap == null) return;
synchronized (mClassName_Tag_Arg4StickyMap) {
for (Map.Entry<String, Object> tagArgEntry : tagArgMap.entrySet()) {
postInner(tagArgEntry.getKey(), tagArgEntry.getValue());
}
}
}
private void unregisterInner(final Object bus) {
if (bus == null) return;
String className = bus.getClass().getName();
synchronized (mClassName_BusesMap) {
Set<Object> buses = mClassName_BusesMap.get(className);
if (buses == null || !buses.contains(bus)) {
System.out.println("The bus of <" + bus + "> was not registered before.");
return;
}
buses.remove(bus);
}
}
private void postInner(final String tag, final Object arg) {
postInner(tag, arg, false);
}
private void postInner(final String tag, final Object arg, final boolean sticky) {
List<BusInfo> busInfoList = mTag_BusInfoListMap.get(tag);
if (busInfoList == null) {
System.out.println("The bus of tag <" + tag + "> is not exists.");
return;
}
for (BusInfo busInfo : busInfoList) {
if (busInfo.method == null) {
Method method = getMethodByBusInfo(busInfo);
if (method == null) {
return;
}
busInfo.method = method;
}
invokeMethod(tag, arg, busInfo, sticky);
}
}
private Method getMethodByBusInfo(BusInfo busInfo) {
try {
if ("".equals(busInfo.paramType)) {
return Class.forName(busInfo.className).getDeclaredMethod(busInfo.funName);
} else {
return Class.forName(busInfo.className).getDeclaredMethod(busInfo.funName, getClassName(busInfo.paramType));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
private Class getClassName(String paramType) throws ClassNotFoundException {
switch (paramType) {
case "boolean":
return boolean.class;
case "int":
return int.class;
case "long":
return long.class;
case "short":
return short.class;
case "byte":
return byte.class;
case "double":
return double.class;
case "float":
return float.class;
case "char":
return char.class;
default:
return Class.forName(paramType);
}
}
private void invokeMethod(final String tag, final Object arg, final BusInfo busInfo, final boolean sticky) {
Runnable runnable = new Runnable() {
@Override
public void run() {
realInvokeMethod(tag, arg, busInfo, sticky);
}
};
switch (busInfo.threadMode) {
// case "MAIN":
// Utils.runOnUiThread(runnable);
// return;
// case "IO":
// ThreadUtils.getIoPool().execute(runnable);
// return;
// case "CPU":
// ThreadUtils.getCpuPool().execute(runnable);
// return;
// case "CACHED":
// ThreadUtils.getCachedPool().execute(runnable);
// return;
// case "SINGLE":
// ThreadUtils.getSinglePool().execute(runnable);
// return;
default:
runnable.run();
}
}
private void realInvokeMethod(final String tag, Object arg, BusInfo busInfo, boolean sticky) {
Set<Object> buses = new HashSet<>();
for (String className : busInfo.classNames) {
Set<Object> subBuses = mClassName_BusesMap.get(className);
if (subBuses != null && !subBuses.isEmpty()) {
buses.addAll(subBuses);
}
}
if (buses.size() == 0) {
if (!sticky) {
System.out.println("The bus of tag <" + tag + "> was not registered before.");
return;
} else {
return;
}
}
try {
if (arg == NULL) {
for (Object bus : buses) {
busInfo.method.invoke(bus);
}
} else {
for (Object bus : buses) {
busInfo.method.invoke(bus, arg);
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private void postStickyInner(final String tag, final Object arg) {
List<BusInfo> busInfoList = mTag_BusInfoListMap.get(tag);
if (busInfoList == null) {
System.out.println("The bus of tag <" + tag + "> is not exists.");
return;
}
for (BusInfo busInfo : busInfoList) {
if (!busInfo.sticky) { // not sticky bus will post directly.
postInner(tag, arg);
return;
}
synchronized (mClassName_Tag_Arg4StickyMap) {
Map<String, Object> tagArgMap = mClassName_Tag_Arg4StickyMap.get(busInfo.className);
if (tagArgMap == null) {
tagArgMap = new HashMap<>();
mClassName_Tag_Arg4StickyMap.put(busInfo.className, tagArgMap);
}
tagArgMap.put(tag, arg);
}
postInner(tag, arg, true);
}
}
private void removeStickyInner(final String tag) {
List<BusInfo> busInfoList = mTag_BusInfoListMap.get(tag);
if (busInfoList == null) {
System.out.println("The bus of tag <" + tag + "> is not exists.");
return;
}
for (BusInfo busInfo : busInfoList) {
if (!busInfo.sticky) {
System.out.println("The bus of tag <" + tag + "> is not sticky.");
return;
}
synchronized (mClassName_Tag_Arg4StickyMap) {
Map<String, Object> tagArgMap = mClassName_Tag_Arg4StickyMap.get(busInfo.className);
if (tagArgMap == null || !tagArgMap.containsKey(tag)) {
System.out.println("The sticky bus of tag <" + tag + "> didn't post.");
return;
}
tagArgMap.remove(tag);
}
}
}
private static final class BusInfo {
String className;
String funName;
String paramType;
String paramName;
boolean sticky;
String threadMode;
int priority;
Method method;
List<String> classNames;
BusInfo(String className, String funName, String paramType, String paramName,
boolean sticky, String threadMode, int priority) {
this.className = className;
this.funName = funName;
this.paramType = paramType;
this.paramName = paramName;
this.sticky = sticky;
this.threadMode = threadMode;
this.priority = priority;
this.classNames = new CopyOnWriteArrayList<>();
}
@Override
public String toString() {
return "BusInfo { desc: " + className + "#" + funName +
("".equals(paramType) ? "()" : ("(" + paramType + " " + paramName + ")")) +
", sticky: " + sticky +
", threadMode: " + threadMode +
", method: " + method +
", priority: " + priority +
" }";
}
}
public enum ThreadMode {
MAIN, IO, CPU, CACHED, SINGLE, POSTING
}
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.CLASS)
public @interface Bus {
String tag();
boolean sticky() default false;
ThreadMode threadMode() default ThreadMode.POSTING;
int priority() default 0;
}
private static class LazyHolder {
private static final BusUtils INSTANCE = new BusUtils();
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/plugin/bus-gradle-plugin/src/main/java/com/blankj/bus/BusInfo.java | plugin/bus-gradle-plugin/src/main/java/com/blankj/bus/BusInfo.java | package com.blankj.bus;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/10
* desc :
* </pre>
*/
public class BusInfo {
public String className; // 函数所在类名
public String funName; // 方法名
public List<ParamsInfo> paramsInfo; // 参数列表信息
public boolean sticky; // 是否粘性
public String threadMode; // 线程模式
public int priority; // 优先级
public boolean isParamSizeNoMoreThanOne; // 参数是否不多于 1 个
public BusInfo(String className, String funName) {
this.className = className;
this.funName = funName;
paramsInfo = new ArrayList<>();
sticky = false;
threadMode = "POSTING";
priority = 0;
isParamSizeNoMoreThanOne = true;
}
@Override
public String toString() {
String paramsInfoString = paramsInfo.toString();
return "{ desc: " + className + "#" + funName +
"(" + paramsInfoString.substring(1, paramsInfoString.length() - 1) + ")" +
(!sticky ? "" : ", sticky: true") +
(threadMode.equals("POSTING") ? "" : ", threadMode: " + threadMode) +
(priority == 0 ? "" : ", priority: " + priority) +
(isParamSizeNoMoreThanOne ? "" : ", paramSize: " + paramsInfo.size()) +
" }";
}
public static class ParamsInfo {
public String className;
public String name;
public ParamsInfo(String className, String name) {
this.className = className;
this.name = name;
}
@Override
public String toString() {
return ("".equals(className) ? "" : (className + " " + name));
}
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/plugin/bus-gradle-plugin/src/main/java/com/blankj/bus/BusUtilsClassVisitor.java | plugin/bus-gradle-plugin/src/main/java/com/blankj/bus/BusUtilsClassVisitor.java | package com.blankj.bus;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.AdviceAdapter;
import java.util.List;
import java.util.Map;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/09
* desc :
* </pre>
*/
public class BusUtilsClassVisitor extends ClassVisitor {
private Map<String, List<BusInfo>> mBusMap;
private String mBusUtilsClass;
public BusUtilsClassVisitor(ClassVisitor classVisitor, Map<String, List<BusInfo>> busMap, String busUtilsClass) {
super(Opcodes.ASM5, classVisitor);
mBusMap = busMap;
mBusUtilsClass = busUtilsClass.replace(".", "/");
}
@Override
public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
if (!"init".equals(name)) {
return super.visitMethod(access, name, descriptor, signature, exceptions);
}
// 往 init() 函数中写入
if (cv == null) return null;
MethodVisitor mv = cv.visitMethod(access, name, descriptor, signature, exceptions);
mv = new AdviceAdapter(Opcodes.ASM5, mv, access, name, descriptor) {
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
return super.visitAnnotation(desc, visible);
}
@Override
protected void onMethodEnter() {
super.onMethodEnter();
}
@Override
protected void onMethodExit(int opcode) {
super.onMethodExit(opcode);
for (Map.Entry<String, List<BusInfo>> busEntry : mBusMap.entrySet()) {
List<BusInfo> infoList = busEntry.getValue();
for (BusInfo busInfo : infoList) {
if (!busInfo.isParamSizeNoMoreThanOne) continue;
mv.visitVarInsn(ALOAD, 0);
mv.visitLdcInsn(busEntry.getKey());
mv.visitLdcInsn(busInfo.className);
mv.visitLdcInsn(busInfo.funName);
if (busInfo.paramsInfo.size() == 1) {
mv.visitLdcInsn(busInfo.paramsInfo.get(0).className);
mv.visitLdcInsn(busInfo.paramsInfo.get(0).name);
} else {
mv.visitLdcInsn("");
mv.visitLdcInsn("");
}
mv.visitInsn(busInfo.sticky ? ICONST_1 : ICONST_0);
mv.visitLdcInsn(busInfo.threadMode);
mv.visitIntInsn(SIPUSH, busInfo.priority);
mv.visitMethodInsn(INVOKESPECIAL, mBusUtilsClass, "registerBus", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZLjava/lang/String;I)V", false);
}
}
}
};
return mv;
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/plugin/bus-gradle-plugin/src/main/java/com/blankj/bus/BusClassVisitor.java | plugin/bus-gradle-plugin/src/main/java/com/blankj/bus/BusClassVisitor.java | package com.blankj.bus;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.AdviceAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/09
* desc :
* </pre>
*/
public class BusClassVisitor extends ClassVisitor {
private Map<String, List<BusInfo>> mBusMap;
private String className;
private BusInfo busInfo;
private String tag;
private String funParamDesc;
private String mBusUtilsClass;
private boolean isStartVisitParams;
public BusClassVisitor(ClassVisitor classVisitor, Map<String, List<BusInfo>> busMap, String busUtilsClass) {
super(Opcodes.ASM5, classVisitor);
mBusMap = busMap;
mBusUtilsClass = busUtilsClass.replace(".", "/");
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
className = name.replace("/", ".");
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public MethodVisitor visitMethod(int access, String funName, String desc, String signature, String[] exceptions) {
if (cv == null) return null;
MethodVisitor mv = cv.visitMethod(access, funName, desc, signature, exceptions);
busInfo = null;
isStartVisitParams = false;
mv = new AdviceAdapter(Opcodes.ASM5, mv, access, funName, desc) {
@Override
public AnnotationVisitor visitAnnotation(String desc1, boolean visible) {
final AnnotationVisitor av = super.visitAnnotation(desc1, visible);
if (("L" + mBusUtilsClass + "$Bus;").equals(desc1)) {
busInfo = new BusInfo(className, funName);
funParamDesc = desc.substring(1, desc.indexOf(")"));
return new AnnotationVisitor(Opcodes.ASM5, av) {
@Override
public void visit(String name, Object value) {// 可获取注解的值
super.visit(name, value);
if ("tag".equals(name)) {
tag = (String) value;
} else if ("sticky".equals(name) && (Boolean) value) {
busInfo.sticky = true;
} else if ("priority".equals(name)) {
busInfo.priority = (int) value;
}
}
@Override
public void visitEnum(String name, String desc, String value) {
super.visitEnum(name, desc, value);
if ("threadMode".equals(name)) {
busInfo.threadMode = value;
}
}
};
}
return av;
}
@Override
public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
super.visitLocalVariable(name, desc, signature, start, end, index);// 获取方法参数信息
if (busInfo != null && !funParamDesc.equals("")) {
if (!isStartVisitParams && index != 0) {
return;
}
isStartVisitParams = true;
if ("this".equals(name)) {
return;
}
funParamDesc = funParamDesc.substring(desc.length());// 每次去除参数直到为 "",那么之后的就不是参数了
busInfo.paramsInfo.add(new BusInfo.ParamsInfo(Type.getType(desc).getClassName(), name));
if (busInfo.isParamSizeNoMoreThanOne && busInfo.paramsInfo.size() > 1) {
busInfo.isParamSizeNoMoreThanOne = false;
}
}
}
@Override
public void visitEnd() {
super.visitEnd();
if (busInfo != null) {
List<BusInfo> infoList = mBusMap.get(tag);
if (infoList == null) {
infoList = new ArrayList<>();
mBusMap.put(tag, infoList);
}
infoList.add(busInfo);
}
}
};
return mv;
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/plugin/api-gradle-plugin/src/test/java/com/blankj/api/ApiTest.java | plugin/api-gradle-plugin/src/test/java/com/blankj/api/ApiTest.java | package com.blankj.api;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/09
* desc :
* </pre>
*/
public class ApiTest {
@Test
public void testInject() throws IOException {
inject2ApiUtils(getApiImplMap());
}
private static Map<String, ApiInfo> getApiImplMap() throws IOException {
Map<String, ApiInfo> apiImplMap = new HashMap<>();
List<String> apiClasses = new ArrayList<>();
ClassReader cr = new ClassReader(TestApiImpl.class.getName());
ClassWriter cw = new ClassWriter(cr, 0);
ClassVisitor cv = new ApiClassVisitor(cw, apiImplMap, apiClasses, ApiUtils.class.getCanonicalName());
cr.accept(cv, ClassReader.SKIP_FRAMES);
System.out.println("apiImplMap = " + apiImplMap);
apiClasses = new ArrayList<>();
cr = new ClassReader(TestApi.class.getName());
cw = new ClassWriter(cr, 0);
cv = new ApiClassVisitor(cw, apiImplMap, apiClasses, ApiUtils.class.getCanonicalName());
cr.accept(cv, ClassReader.SKIP_FRAMES);
System.out.println("apiClasses = " + apiClasses);
return apiImplMap;
}
private static void inject2ApiUtils(Map<String, ApiInfo> apiImpls) throws IOException {
ClassReader cr = new ClassReader(ApiUtils.class.getName());
ClassWriter cw = new ClassWriter(cr, 0);
ClassVisitor cv = new ApiUtilsClassVisitor(cw, apiImpls, ApiUtils.class.getCanonicalName());
cr.accept(cv, ClassReader.SKIP_FRAMES);
FileUtils.writeByteArrayToFile(new File("ApiUtils2333.class"), cw.toByteArray());
}
@ApiUtils.Api(isMock = true)
public static class TestApiImpl extends TestApi {
@Override
public String test(String param) {
System.out.println("param = " + param);
return "haha";
}
}
public static abstract class TestApi extends ApiUtils.BaseApi {
public abstract String test(String name);
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/plugin/api-gradle-plugin/src/test/java/com/blankj/api/ApiUtils.java | plugin/api-gradle-plugin/src/test/java/com/blankj/api/ApiUtils.java | package com.blankj.api;
import com.android.annotations.NonNull;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/09
* desc :
* </pre>
*/
public class ApiUtils {
private static final String TAG = "ApiUtils";
private Map<Class, BaseApi> mApiMap = new ConcurrentHashMap<>();
private Map<Class, Class> mInjectApiImplMap = new HashMap<>();
private ApiUtils() {
init();
}
/**
* It'll be injected the implClasses who have {@link ApiUtils.Api} annotation
* by function of {@link ApiUtils#registerImpl} when execute transform task.
*/
private void init() {/*inject*/}
private void registerImpl(Class implClass) {
mInjectApiImplMap.put(implClass.getSuperclass(), implClass);
}
/**
* Get api.
*
* @param apiClass The class of api.
* @param <T> The type.
* @return the api
*/
public static <T extends BaseApi> T getApi(@NonNull final Class<T> apiClass) {
return getInstance().getApiInner(apiClass);
}
public static String toString_() {
return getInstance().toString();
}
@Override
public String toString() {
return "ApiUtils: " + mInjectApiImplMap;
}
private static ApiUtils getInstance() {
return LazyHolder.INSTANCE;
}
private <Result> Result getApiInner(Class apiClass) {
BaseApi api = mApiMap.get(apiClass);
if (api == null) {
synchronized (this) {
api = mApiMap.get(apiClass);
if (api == null) {
Class implClass = mInjectApiImplMap.get(apiClass);
if (implClass != null) {
try {
api = (BaseApi) implClass.newInstance();
mApiMap.put(apiClass, api);
} catch (Exception ignore) {
System.out.println("The <" + implClass + "> has no parameterless constructor.");
return null;
}
} else {
System.out.println("The <" + apiClass + "> doesn't implement.");
return null;
}
}
}
}
//noinspection unchecked
return (Result) api;
}
private static class LazyHolder {
private static final ApiUtils INSTANCE = new ApiUtils();
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.CLASS)
public @interface Api {
boolean isMock() default false;
}
public abstract static class BaseApi {
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/plugin/api-gradle-plugin/src/main/java/com/blankj/api/ApiClassVisitor.java | plugin/api-gradle-plugin/src/main/java/com/blankj/api/ApiClassVisitor.java | package com.blankj.api;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Opcodes;
import java.util.List;
import java.util.Map;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/09
* desc :
* </pre>
*/
public class ApiClassVisitor extends ClassVisitor {
private Map<String, ApiInfo> mApiImplMap;
private List<String> mApiClasses;
private String className;
private String superClassName;
private boolean hasAnnotation;
private boolean isMock;
private String mApiUtilsClass;
public ApiClassVisitor(ClassVisitor classVisitor, Map<String, ApiInfo> apiImplMap, List<String> apiClasses, String apiUtilsClass) {
super(Opcodes.ASM5, classVisitor);
mApiImplMap = apiImplMap;
mApiClasses = apiClasses;
mApiUtilsClass = apiUtilsClass.replace(".", "/");
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
className = name;
superClassName = superName;
if ((mApiUtilsClass + "$BaseApi").equals(superName)) {
mApiClasses.add(name);
}
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
if (("L" + mApiUtilsClass + "$Api;").equals(desc)) {
hasAnnotation = true;
return new AnnotationVisitor(Opcodes.ASM5, super.visitAnnotation(desc, visible)) {
@Override
public void visit(String name, Object value) {// 可获取注解的值
isMock = (boolean) value;
super.visit(name, value);
}
};
}
return super.visitAnnotation(desc, visible);
}
@Override
public void visitEnd() {
super.visitEnd();
if (hasAnnotation) {
if (!isMock) {// 如果不是 mock 的话
ApiInfo apiInfo = mApiImplMap.get(superClassName);
if (apiInfo == null || apiInfo.isMock) {// 不存在或者之前存在的是 mock
mApiImplMap.put(superClassName, new ApiInfo(className, false));
} else {// 存在一个 api 多个非 mock 实现就报错
throw new IllegalArgumentException("<" + className + "> and <" + apiInfo.implApiClass + "> impl same api of <" + superClassName + ">");
}
} else {// mock 的话,如果 map 中已存在就不覆盖了
if (!mApiImplMap.containsKey(superClassName)) {
mApiImplMap.put(superClassName, new ApiInfo(className, true));
}
}
}
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/plugin/api-gradle-plugin/src/main/java/com/blankj/api/ApiUtilsClassVisitor.java | plugin/api-gradle-plugin/src/main/java/com/blankj/api/ApiUtilsClassVisitor.java | package com.blankj.api;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.AdviceAdapter;
import java.util.Map;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/09
* desc :
* </pre>
*/
public class ApiUtilsClassVisitor extends ClassVisitor {
private Map<String, ApiInfo> mApiImplMap;
private String mApiUtilsClass;
public ApiUtilsClassVisitor(ClassVisitor classVisitor, Map<String, ApiInfo> apiImplMap, String apiUtilsClass) {
super(Opcodes.ASM5, classVisitor);
mApiImplMap = apiImplMap;
mApiUtilsClass = apiUtilsClass.replace(".", "/");
}
@Override
public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
if (!"init".equals(name)) {
return super.visitMethod(access, name, descriptor, signature, exceptions);
}
// 往 init() 函数中写入
if (cv == null) return null;
MethodVisitor mv = cv.visitMethod(access, name, descriptor, signature, exceptions);
mv = new AdviceAdapter(Opcodes.ASM5, mv, access, name, descriptor) {
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
return super.visitAnnotation(desc, visible);
}
@Override
protected void onMethodEnter() {
super.onMethodEnter();
}
@Override
protected void onMethodExit(int opcode) {
super.onMethodExit(opcode);
for (Map.Entry<String, ApiInfo> apiImplEntry : mApiImplMap.entrySet()) {
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitLdcInsn(Type.getType("L" + apiImplEntry.getValue().implApiClass + ";"));
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, mApiUtilsClass, "registerImpl", "(Ljava/lang/Class;)V", false);
}
}
};
return mv;
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/plugin/api-gradle-plugin/src/main/java/com/blankj/api/ApiInfo.java | plugin/api-gradle-plugin/src/main/java/com/blankj/api/ApiInfo.java | package com.blankj.api;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/07/14
* desc :
* </pre>
*/
public class ApiInfo {
public String implApiClass;
public boolean isMock;
public ApiInfo(String implApiClass, boolean isMock) {
this.implApiClass = implApiClass;
this.isMock = isMock;
}
@Override
public String toString() {
return "{ implApiClass: " + implApiClass +
", isMock: " + isMock +
" }";
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/plugin/lib/base-transform/src/main/java/com/blankj/base_transform/util/ZipUtils.java | plugin/lib/base-transform/src/main/java/com/blankj/base_transform/util/ZipUtils.java | package com.blankj.base_transform.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/08/27
* desc : utils about zip or jar
* </pre>
*/
public final class ZipUtils {
private static final int BUFFER_LEN = 8192;
private ZipUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Zip the files.
*
* @param srcFiles The source of files.
* @param zipFilePath The path of ZIP file.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFiles(final Collection<String> srcFiles,
final String zipFilePath)
throws IOException {
return zipFiles(srcFiles, zipFilePath, null);
}
/**
* Zip the files.
*
* @param srcFilePaths The paths of source files.
* @param zipFilePath The path of ZIP file.
* @param comment The comment.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFiles(final Collection<String> srcFilePaths,
final String zipFilePath,
final String comment)
throws IOException {
if (srcFilePaths == null || zipFilePath == null) return false;
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipFilePath));
for (String srcFile : srcFilePaths) {
if (!zipFile(getFileByPath(srcFile), "", zos, comment)) return false;
}
return true;
} finally {
if (zos != null) {
zos.finish();
zos.close();
}
}
}
/**
* Zip the files.
*
* @param srcFiles The source of files.
* @param zipFile The ZIP file.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFiles(final Collection<File> srcFiles, final File zipFile)
throws IOException {
return zipFiles(srcFiles, zipFile, null);
}
/**
* Zip the files.
*
* @param srcFiles The source of files.
* @param zipFile The ZIP file.
* @param comment The comment.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFiles(final Collection<File> srcFiles,
final File zipFile,
final String comment)
throws IOException {
if (srcFiles == null || zipFile == null) return false;
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipFile));
for (File srcFile : srcFiles) {
if (!zipFile(srcFile, "", zos, comment)) return false;
}
return true;
} finally {
if (zos != null) {
zos.finish();
zos.close();
}
}
}
/**
* Zip the file.
*
* @param srcFilePath The path of source file.
* @param zipFilePath The path of ZIP file.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFile(final String srcFilePath,
final String zipFilePath)
throws IOException {
return zipFile(getFileByPath(srcFilePath), getFileByPath(zipFilePath), null);
}
/**
* Zip the file.
*
* @param srcFilePath The path of source file.
* @param zipFilePath The path of ZIP file.
* @param comment The comment.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFile(final String srcFilePath,
final String zipFilePath,
final String comment)
throws IOException {
return zipFile(getFileByPath(srcFilePath), getFileByPath(zipFilePath), comment);
}
/**
* Zip the file.
*
* @param srcFile The source of file.
* @param zipFile The ZIP file.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFile(final File srcFile,
final File zipFile)
throws IOException {
return zipFile(srcFile, zipFile, null);
}
/**
* Zip the file.
*
* @param srcFile The source of file.
* @param zipFile The ZIP file.
* @param comment The comment.
* @return {@code true}: success<br>{@code false}: fail
* @throws IOException if an I/O error has occurred
*/
public static boolean zipFile(final File srcFile,
final File zipFile,
final String comment)
throws IOException {
if (srcFile == null || zipFile == null) return false;
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipFile));
return zipFile(srcFile, "", zos, comment);
} finally {
if (zos != null) {
zos.close();
}
}
}
private static boolean zipFile(final File srcFile,
String rootPath,
final ZipOutputStream zos,
final String comment)
throws IOException {
rootPath = rootPath + (isSpace(rootPath) ? "" : File.separator) + srcFile.getName();
if (srcFile.isDirectory()) {
File[] fileList = srcFile.listFiles();
if (fileList == null || fileList.length <= 0) {
ZipEntry entry = new ZipEntry(rootPath + '/');
entry.setComment(comment);
zos.putNextEntry(entry);
zos.closeEntry();
} else {
for (File file : fileList) {
if (!zipFile(file, rootPath, zos, comment)) return false;
}
}
} else {
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(srcFile));
ZipEntry entry = new ZipEntry(rootPath);
entry.setComment(comment);
zos.putNextEntry(entry);
byte buffer[] = new byte[BUFFER_LEN];
int len;
while ((len = is.read(buffer, 0, BUFFER_LEN)) != -1) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
} finally {
if (is != null) {
is.close();
}
}
}
return true;
}
/**
* Unzip the file.
*
* @param zipFilePath The path of ZIP file.
* @param destDirPath The path of destination directory.
* @return the unzipped files
* @throws IOException if unzip unsuccessfully
*/
public static List<File> unzipFile(final String zipFilePath,
final String destDirPath)
throws IOException {
return unzipFileByKeyword(zipFilePath, destDirPath, null);
}
/**
* Unzip the file.
*
* @param zipFile The ZIP file.
* @param destDir The destination directory.
* @return the unzipped files
* @throws IOException if unzip unsuccessfully
*/
public static List<File> unzipFile(final File zipFile,
final File destDir)
throws IOException {
return unzipFileByKeyword(zipFile, destDir, null);
}
/**
* Unzip the file by keyword.
*
* @param zipFilePath The path of ZIP file.
* @param destDirPath The path of destination directory.
* @param keyword The keyboard.
* @return the unzipped files
* @throws IOException if unzip unsuccessfully
*/
public static List<File> unzipFileByKeyword(final String zipFilePath,
final String destDirPath,
final String keyword)
throws IOException {
return unzipFileByKeyword(getFileByPath(zipFilePath), getFileByPath(destDirPath), keyword);
}
/**
* Unzip the file by keyword.
*
* @param zipFile The ZIP file.
* @param destDir The destination directory.
* @param keyword The keyboard.
* @return the unzipped files
* @throws IOException if unzip unsuccessfully
*/
public static List<File> unzipFileByKeyword(final File zipFile,
final File destDir,
final String keyword)
throws IOException {
if (zipFile == null || destDir == null) return null;
List<File> files = new ArrayList<>();
ZipFile zip = new ZipFile(zipFile);
Enumeration<?> entries = zip.entries();
try {
if (isSpace(keyword)) {
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String entryName = entry.getName();
if (entryName.contains("../")) {
System.err.println("entryName: " + entryName + " is dangerous!");
continue;
}
if (!unzipChildFile(destDir, files, zip, entry, entryName)) return files;
}
} else {
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String entryName = entry.getName();
if (entryName.contains("../")) {
System.out.println("entryName: " + entryName + " is dangerous!");
continue;
}
if (entryName.contains(keyword)) {
if (!unzipChildFile(destDir, files, zip, entry, entryName)) return files;
}
}
}
} finally {
zip.close();
}
return files;
}
private static boolean unzipChildFile(final File destDir,
final List<File> files,
final ZipFile zip,
final ZipEntry entry,
final String name) throws IOException {
File file = new File(destDir, name);
files.add(file);
if (entry.isDirectory()) {
return createOrExistsDir(file);
} else {
if (!createOrExistsFile(file)) return false;
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(zip.getInputStream(entry));
out = new BufferedOutputStream(new FileOutputStream(file));
byte buffer[] = new byte[BUFFER_LEN];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
return true;
}
/**
* Return the files' path in ZIP file.
*
* @param zipFilePath The path of ZIP file.
* @return the files' path in ZIP file
* @throws IOException if an I/O error has occurred
*/
public static List<String> getFilesPath(final String zipFilePath)
throws IOException {
return getFilesPath(getFileByPath(zipFilePath));
}
/**
* Return the files' path in ZIP file.
*
* @param zipFile The ZIP file.
* @return the files' path in ZIP file
* @throws IOException if an I/O error has occurred
*/
public static List<String> getFilesPath(final File zipFile)
throws IOException {
if (zipFile == null) return null;
List<String> paths = new ArrayList<>();
ZipFile zip = new ZipFile(zipFile);
Enumeration<?> entries = zip.entries();
while (entries.hasMoreElements()) {
String entryName = ((ZipEntry) entries.nextElement()).getName();
if (entryName.contains("../")) {
System.out.println("entryName: " + entryName + " is dangerous!");
paths.add(entryName);
} else {
paths.add(entryName);
}
}
zip.close();
return paths;
}
/**
* Return the files' comment in ZIP file.
*
* @param zipFilePath The path of ZIP file.
* @return the files' comment in ZIP file
* @throws IOException if an I/O error has occurred
*/
public static List<String> getComments(final String zipFilePath)
throws IOException {
return getComments(getFileByPath(zipFilePath));
}
/**
* Return the files' comment in ZIP file.
*
* @param zipFile The ZIP file.
* @return the files' comment in ZIP file
* @throws IOException if an I/O error has occurred
*/
public static List<String> getComments(final File zipFile)
throws IOException {
if (zipFile == null) return null;
List<String> comments = new ArrayList<>();
ZipFile zip = new ZipFile(zipFile);
Enumeration<?> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
comments.add(entry.getComment());
}
zip.close();
return comments;
}
private static boolean createOrExistsDir(final File file) {
return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
}
private static boolean createOrExistsFile(final File file) {
if (file == null) return false;
if (file.exists()) return file.isFile();
if (!createOrExistsDir(file.getParentFile())) return false;
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private static File getFileByPath(final String filePath) {
return isSpace(filePath) ? null : new File(filePath);
}
private static boolean isSpace(final String s) {
if (s == null) return true;
for (int i = 0, len = s.length(); i < len; ++i) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/UtilCodeApiImpl.java | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/UtilCodeApiImpl.java | package com.blankj.utilcode.pkg;
import android.content.Context;
import com.blankj.utilcode.export.api.UtilCodeApi;
import com.blankj.utilcode.pkg.feature.CoreUtilActivity;
import com.blankj.utilcode.util.ApiUtils;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/01
* desc :
* </pre>
*/
@ApiUtils.Api
public class UtilCodeApiImpl extends UtilCodeApi {
@Override
public void startUtilCodeActivity(Context context) {
CoreUtilActivity.Companion.start(context);
}
@Override
public void testCallback(Callback callback) {
if (callback != null) {
callback.call();
}
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpActivity.java | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpActivity.java | package com.blankj.utilcode.pkg.feature.mvp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.blankj.common.activity.CommonActivity;
import com.blankj.utilcode.pkg.R;
import androidx.annotation.Nullable;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/11/09
* desc :
* </pre>
*/
public class MvpActivity extends CommonActivity {
public static void start(Context context) {
Intent starter = new Intent(context, MvpActivity.class);
context.startActivity(starter);
}
@Override
public int bindTitleRes() {
return R.string.demo_mvp;
}
@Override
public int bindLayout() {
return R.layout.mvp_activity;
}
@Override
public void initView(@Nullable Bundle savedInstanceState, @Nullable View contentView) {
super.initView(savedInstanceState, contentView);
new MvpView(this).addPresenter(new MvpPresenter());
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpPresenter.java | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpPresenter.java | package com.blankj.utilcode.pkg.feature.mvp;
import com.blankj.base.mvp.BasePresenter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/11/26
* desc :
* </pre>
*/
public class MvpPresenter extends BasePresenter<MvpView>
implements MvpMvp.Presenter {
@Override
public void onBindView() {
}
@Override
public void updateMsg() {
getView().setLoadingVisible(true);
getModel(MvpModel.class).requestUpdateMsg(new Utils.Consumer<String>() {
@Override
public void accept(String s) {
if (isAlive()) {
getView().showMsg(s);
getView().setLoadingVisible(false);
} else {
LogUtils.iTag(MvpView.TAG, "destroyed");
}
}
});
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpModel.java | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpModel.java | package com.blankj.utilcode.pkg.feature.mvp;
import com.blankj.base.mvp.BaseModel;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.Utils;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/11/26
* desc :
* </pre>
*/
public class MvpModel extends BaseModel implements MvpMvp.Model {
private int index;
@Override
public void onCreate() {
index = 0;
}
@Override
public void requestUpdateMsg(final Utils.Consumer<String> consumer) {
ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<String>() {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(2000);
return "msg: " + index++;
}
@Override
public void onSuccess(String result) {
consumer.accept(result);
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpView.java | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpView.java | package com.blankj.utilcode.pkg.feature.mvp;
import android.text.Layout;
import android.view.View;
import android.widget.TextView;
import com.blankj.base.mvp.BaseView;
import com.blankj.utilcode.pkg.R;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/11/26
* desc :
* </pre>
*/
public class MvpView extends BaseView<MvpView>
implements MvpMvp.View {
private TextView mvpTv;
private TextView mvpMeasureWidthTv;
private int i = 0;
public MvpView(MvpActivity activity) {
super(activity);
mvpTv = activity.findViewById(R.id.mvpUpdateTv);
ClickUtils.applyPressedBgDark(mvpTv);
mvpTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getPresenter(MvpPresenter.class).updateMsg();
}
});
mvpMeasureWidthTv = activity.findViewById(R.id.mvpMeasureWidthTv);
measure();
}
private void measure() {
ThreadUtils.runOnUiThreadDelayed(new Runnable() {
@Override
public void run() {
float textWidth = Layout.getDesiredWidth(mvpMeasureWidthTv.getText(), mvpMeasureWidthTv.getPaint()) + SizeUtils.dp2px(16);
float textWidth2 = mvpMeasureWidthTv.getPaint().measureText(mvpMeasureWidthTv.getText().toString()) + SizeUtils.dp2px(16);
LogUtils.i(mvpMeasureWidthTv.getWidth(), textWidth, textWidth2);
mvpMeasureWidthTv.setText(mvpMeasureWidthTv.getText().toString() + i);
measure();
}
}, 1000);
}
@Override
public void setLoadingVisible(boolean visible) {
final MvpActivity activity = getActivity();
if (visible) {
activity.showLoading(new Runnable() {
@Override
public void run() {
activity.finish();
}
});
} else {
activity.dismissLoading();
}
}
@Override
public void showMsg(CharSequence msg) {
ToastUtils.showLong(msg);
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpMvp.java | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/mvp/MvpMvp.java | package com.blankj.utilcode.pkg.feature.mvp;
import com.blankj.utilcode.util.Utils;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/11/26
* desc :
* </pre>
*/
public interface MvpMvp {
interface View {
void setLoadingVisible(boolean visible);
void showMsg(CharSequence msg);
}
interface Presenter {
void updateMsg();
}
interface Model {
void requestUpdateMsg(final Utils.Consumer<String> consumer);
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/api/other/pkg/OtherPkgApiImpl.java | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/api/other/pkg/OtherPkgApiImpl.java | package com.blankj.utilcode.pkg.feature.api.other.pkg;
import com.blankj.utilcode.pkg.feature.api.other.export.OtherModuleApi;
import com.blankj.utilcode.util.ApiUtils;
import com.blankj.utilcode.util.ToastUtils;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/10
* desc : demo about ApiUtils
* </pre>
*/
@ApiUtils.Api
public class OtherPkgApiImpl extends OtherModuleApi {
@Override
public void invokeWithParams(ApiBean bean) {
ToastUtils.showShort(bean.name);
}
@Override
public ApiBean invokeWithReturnValue() {
String value = "value";
return new ApiBean(value);
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/api/other/export/OtherModuleApi.java | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/api/other/export/OtherModuleApi.java | package com.blankj.utilcode.pkg.feature.api.other.export;
import com.blankj.utilcode.util.ApiUtils;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/10
* desc : demo about ApiUtils
* </pre>
*/
public abstract class OtherModuleApi extends ApiUtils.BaseApi {
public abstract void invokeWithParams(ApiBean bean);
public abstract ApiBean invokeWithReturnValue();
public static class ApiBean {
public String name;
public ApiBean(String name) {
this.name = name;
}
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/reflect/TestPrivateStaticFinal.java | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/reflect/TestPrivateStaticFinal.java | package com.blankj.utilcode.pkg.feature.reflect;
import androidx.annotation.Keep;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/09/09
* desc :
* </pre>
*/
@Keep
public class TestPrivateStaticFinal {
public static final String STR = "str";
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/utilcode/export/src/main/java/com/blankj/utilcode/export/api/UtilCodeApi.java | feature/utilcode/export/src/main/java/com/blankj/utilcode/export/api/UtilCodeApi.java | package com.blankj.utilcode.export.api;
import android.content.Context;
import com.blankj.utilcode.util.ApiUtils;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/01
* desc :
* </pre>
*/
public abstract class UtilCodeApi extends ApiUtils.BaseApi {
public abstract void startUtilCodeActivity(Context context);
public abstract void testCallback(Callback callback);
public interface Callback {
void call();
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/launcher/app/src/main/java/com/blankj/launcher/app/LauncherApp.java | feature/launcher/app/src/main/java/com/blankj/launcher/app/LauncherApp.java | package com.blankj.launcher.app;
import com.blankj.common.CommonApplication;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/10/12
* desc :
* </pre>
*/
public class LauncherApp extends CommonApplication {
private static LauncherApp sInstance;
public static LauncherApp getInstance() {
return sInstance;
}
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/mock/src/main/java/com/blankj/mock/utilcode/UtilCodeApiMock.java | feature/mock/src/main/java/com/blankj/mock/utilcode/UtilCodeApiMock.java | package com.blankj.mock.utilcode;
import android.content.Context;
import com.blankj.utilcode.export.api.UtilCodeApi;
import com.blankj.utilcode.util.ApiUtils;
import com.blankj.utilcode.util.ToastUtils;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/10
* desc :
* </pre>
*/
@ApiUtils.Api(isMock = true)
public class UtilCodeApiMock extends UtilCodeApi {
@Override
public void startUtilCodeActivity(Context context) {
ToastUtils.showShort("startUtilCodeActivity");
}
@Override
public void testCallback(Callback callback) {
if (callback != null) {
callback.call();
}
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/mock/src/main/java/com/blankj/mock/subutil/SubUtilApiMock.java | feature/mock/src/main/java/com/blankj/mock/subutil/SubUtilApiMock.java | package com.blankj.mock.subutil;
import android.content.Context;
import com.blankj.subutil.export.api.SubUtilApi;
import com.blankj.utilcode.util.ApiUtils;
import com.blankj.utilcode.util.ToastUtils;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/10
* desc :
* </pre>
*/
@ApiUtils.Api(isMock = true)
public class SubUtilApiMock extends SubUtilApi {
@Override
public void startSubUtilActivity(Context context) {
ToastUtils.showShort("startSubUtilActivity");
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/subutil/pkg/src/main/java/com/blankj/subutil/pkg/SubUtilApiImpl.java | feature/subutil/pkg/src/main/java/com/blankj/subutil/pkg/SubUtilApiImpl.java | package com.blankj.subutil.pkg;
import android.content.Context;
import com.blankj.subutil.export.api.SubUtilApi;
import com.blankj.subutil.pkg.feature.SubUtilActivity;
import com.blankj.utilcode.util.ApiUtils;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/02
* desc :
* </pre>
*/
@ApiUtils.Api
public class SubUtilApiImpl extends SubUtilApi {
@Override
public void startSubUtilActivity(Context context) {
SubUtilActivity.Companion.start(context);
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/subutil/export/src/main/java/com/blankj/subutil/export/api/SubUtilApi.java | feature/subutil/export/src/main/java/com/blankj/subutil/export/api/SubUtilApi.java | package com.blankj.subutil.export.api;
import android.content.Context;
import com.blankj.utilcode.util.ApiUtils;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/06/09
* desc :
* </pre>
*/
public abstract class SubUtilApi extends ApiUtils.BaseApi {
public abstract void startSubUtilActivity(Context context);
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/feature/main/app/src/main/java/com/blankj/main/app/MainApp.java | feature/main/app/src/main/java/com/blankj/main/app/MainApp.java | package com.blankj.main.app;
import android.content.Context;
import com.blankj.common.CommonApplication;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/10/12
* desc :
* </pre>
*/
public class MainApp extends CommonApplication {
private static MainApp sInstance;
public static MainApp getInstance() {
return sInstance;
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
}
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/ZipUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/ZipUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static com.blankj.utilcode.util.TestConfig.PATH_TEMP;
import static com.blankj.utilcode.util.TestConfig.PATH_ZIP;
import static junit.framework.TestCase.assertTrue;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/09/10
* desc : test ZipUtils
* </pre>
*/
public class ZipUtilsTest extends BaseTest {
private String zipFile = PATH_TEMP + "zipFile.zip";
private String zipFiles = PATH_TEMP + "zipFiles.zip";
@Before
public void setUp() throws Exception {
FileUtils.createOrExistsDir(PATH_TEMP);
assertTrue(ZipUtils.zipFile(PATH_ZIP, zipFile, "测试zip"));
}
@Test
public void zipFiles() throws Exception {
List<String> files = new ArrayList<>();
files.add(PATH_ZIP + "test.txt");
files.add(PATH_ZIP);
files.add(PATH_ZIP + "testDir");
assertTrue(ZipUtils.zipFiles(files, zipFiles));
}
@Test
public void unzipFile() throws Exception {
System.out.println(ZipUtils.unzipFile(zipFile, PATH_TEMP));
}
@Test
public void unzipFileByKeyword() throws Exception {
System.out.println((ZipUtils.unzipFileByKeyword(zipFile, PATH_TEMP, null)).toString());
}
@Test
public void getFilesPath() throws Exception {
System.out.println(ZipUtils.getFilesPath(zipFile));
}
@Test
public void getComments() throws Exception {
System.out.println(ZipUtils.getComments(zipFile));
}
@After
public void tearDown() {
FileUtils.deleteAllInDir(PATH_TEMP);
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDoubleStaticUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDoubleStaticUtilsTest.java | package com.blankj.utilcode.util;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.Serializable;
import static com.blankj.utilcode.util.TestConfig.FILE_SEP;
import static com.blankj.utilcode.util.TestConfig.PATH_CACHE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/06/13
* desc : test CacheDoubleStaticUtils
* </pre>
*/
public class CacheDoubleStaticUtilsTest extends BaseTest {
private static final String CACHE_PATH = PATH_CACHE + "double" + FILE_SEP;
private static final File CACHE_FILE = new File(CACHE_PATH);
private static final byte[] BYTES = "CacheDoubleUtils".getBytes();
private static final String STRING = "CacheDoubleUtils";
private static final JSONObject JSON_OBJECT = new JSONObject();
private static final JSONArray JSON_ARRAY = new JSONArray();
private static final ParcelableTest PARCELABLE_TEST = new ParcelableTest("Blankj", "CacheDoubleUtils");
private static final SerializableTest SERIALIZABLE_TEST = new SerializableTest("Blankj", "CacheDoubleUtils");
private static final Bitmap BITMAP = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565);
private static final Drawable DRAWABLE = new BitmapDrawable(Utils.getApp().getResources(), BITMAP);
private static final CacheMemoryUtils CACHE_MEMORY_UTILS = CacheMemoryUtils.getInstance();
private static final CacheDiskUtils CACHE_DISK_UTILS = CacheDiskUtils.getInstance(CACHE_FILE);
private static final CacheDoubleUtils CACHE_DOUBLE_UTILS = CacheDoubleUtils.getInstance(CACHE_MEMORY_UTILS, CACHE_DISK_UTILS);
static {
try {
JSON_OBJECT.put("class", "CacheDoubleUtils");
JSON_OBJECT.put("author", "Blankj");
JSON_ARRAY.put(0, JSON_OBJECT);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Before
public void setUp() {
CacheDoubleStaticUtils.setDefaultCacheDoubleUtils(CACHE_DOUBLE_UTILS);
CacheDoubleStaticUtils.put("bytes", BYTES);
CacheDoubleStaticUtils.put("string", STRING);
CacheDoubleStaticUtils.put("jsonObject", JSON_OBJECT);
CacheDoubleStaticUtils.put("jsonArray", JSON_ARRAY);
CacheDoubleStaticUtils.put("bitmap", BITMAP);
CacheDoubleStaticUtils.put("drawable", DRAWABLE);
CacheDoubleStaticUtils.put("parcelable", PARCELABLE_TEST);
CacheDoubleStaticUtils.put("serializable", SERIALIZABLE_TEST);
}
@Test
public void getBytes() {
assertEquals(STRING, new String(CacheDoubleStaticUtils.getBytes("bytes")));
CACHE_MEMORY_UTILS.remove("bytes");
assertEquals(STRING, new String(CacheDoubleStaticUtils.getBytes("bytes")));
CACHE_DISK_UTILS.remove("bytes");
assertNull(CacheDoubleStaticUtils.getBytes("bytes"));
}
@Test
public void getString() {
assertEquals(STRING, CacheDoubleStaticUtils.getString("string"));
CACHE_MEMORY_UTILS.remove("string");
assertEquals(STRING, CacheDoubleStaticUtils.getString("string"));
CACHE_DISK_UTILS.remove("string");
assertNull(CacheDoubleStaticUtils.getString("string"));
}
@Test
public void getJSONObject() {
assertEquals(JSON_OBJECT.toString(), CacheDoubleStaticUtils.getJSONObject("jsonObject").toString());
CACHE_MEMORY_UTILS.remove("jsonObject");
assertEquals(JSON_OBJECT.toString(), CacheDoubleStaticUtils.getJSONObject("jsonObject").toString());
CACHE_DISK_UTILS.remove("jsonObject");
assertNull(CacheDoubleStaticUtils.getJSONObject("jsonObject"));
}
@Test
public void getJSONArray() {
assertEquals(JSON_ARRAY.toString(), CacheDoubleStaticUtils.getJSONArray("jsonArray").toString());
CACHE_MEMORY_UTILS.remove("jsonArray");
assertEquals(JSON_ARRAY.toString(), CacheDoubleStaticUtils.getJSONArray("jsonArray").toString());
CACHE_DISK_UTILS.remove("jsonArray");
assertNull(CacheDoubleStaticUtils.getJSONArray("jsonArray"));
}
@Test
public void getBitmap() {
assertEquals(BITMAP, CacheDoubleStaticUtils.getBitmap("bitmap"));
CACHE_MEMORY_UTILS.remove("bitmap");
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.bitmap2Bytes(CacheDoubleStaticUtils.getBitmap("bitmap"), Bitmap.CompressFormat.PNG, 100)
);
CACHE_DISK_UTILS.remove("bitmap");
assertNull(CacheDoubleStaticUtils.getBitmap("bitmap"));
}
@Test
public void getDrawable() {
assertEquals(DRAWABLE, CacheDoubleStaticUtils.getDrawable("drawable"));
CACHE_MEMORY_UTILS.remove("drawable");
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.drawable2Bytes(CacheDoubleStaticUtils.getDrawable("drawable"), Bitmap.CompressFormat.PNG, 100)
);
CACHE_DISK_UTILS.remove("drawable");
assertNull(CacheDoubleStaticUtils.getDrawable("drawable"));
}
@Test
public void getParcel() {
assertEquals(PARCELABLE_TEST, CacheDoubleStaticUtils.getParcelable("parcelable", ParcelableTest.CREATOR));
CACHE_MEMORY_UTILS.remove("parcelable");
assertEquals(PARCELABLE_TEST, CacheDoubleStaticUtils.getParcelable("parcelable", ParcelableTest.CREATOR));
CACHE_DISK_UTILS.remove("parcelable");
assertNull(CacheDoubleStaticUtils.getParcelable("parcelable", PARCELABLE_TEST.CREATOR));
}
@Test
public void getSerializable() {
assertEquals(SERIALIZABLE_TEST, CacheDoubleStaticUtils.getSerializable("serializable"));
CACHE_MEMORY_UTILS.remove("serializable");
assertEquals(SERIALIZABLE_TEST, CacheDoubleStaticUtils.getSerializable("serializable"));
CACHE_DISK_UTILS.remove("serializable");
assertNull(CacheDoubleStaticUtils.getSerializable("serializable"));
}
@Test
public void getCacheDiskSize() {
assertEquals(FileUtils.getLength(CACHE_FILE), CacheDoubleStaticUtils.getCacheDiskSize());
}
@Test
public void getCacheDiskCount() {
assertEquals(8, CacheDoubleStaticUtils.getCacheDiskCount());
}
@Test
public void getCacheMemoryCount() {
assertEquals(8, CacheDoubleStaticUtils.getCacheMemoryCount());
}
@Test
public void remove() {
assertNotNull(CacheDoubleStaticUtils.getString("string"));
CacheDoubleStaticUtils.remove("string");
assertNull(CacheDoubleStaticUtils.getString("string"));
}
@Test
public void clear() {
assertNotNull(CacheDoubleStaticUtils.getBytes("bytes"));
assertNotNull(CacheDoubleStaticUtils.getString("string"));
assertNotNull(CacheDoubleStaticUtils.getJSONObject("jsonObject"));
assertNotNull(CacheDoubleStaticUtils.getJSONArray("jsonArray"));
assertNotNull(CacheDoubleStaticUtils.getBitmap("bitmap"));
assertNotNull(CacheDoubleStaticUtils.getDrawable("drawable"));
assertNotNull(CacheDoubleStaticUtils.getParcelable("parcelable", ParcelableTest.CREATOR));
assertNotNull(CacheDoubleStaticUtils.getSerializable("serializable"));
CacheDoubleStaticUtils.clear();
assertNull(CacheDoubleStaticUtils.getBytes("bytes"));
assertNull(CacheDoubleStaticUtils.getString("string"));
assertNull(CacheDoubleStaticUtils.getJSONObject("jsonObject"));
assertNull(CacheDoubleStaticUtils.getJSONArray("jsonArray"));
assertNull(CacheDoubleStaticUtils.getBitmap("bitmap"));
assertNull(CacheDoubleStaticUtils.getDrawable("drawable"));
assertNull(CacheDoubleStaticUtils.getParcelable("parcelable", ParcelableTest.CREATOR));
assertNull(CacheDoubleStaticUtils.getSerializable("serializable"));
assertEquals(0, CacheDoubleStaticUtils.getCacheDiskSize());
assertEquals(0, CacheDoubleStaticUtils.getCacheDiskCount());
assertEquals(0, CacheDoubleStaticUtils.getCacheMemoryCount());
}
@After
public void tearDown() {
CacheDoubleStaticUtils.clear();
}
static class ParcelableTest implements Parcelable {
String author;
String className;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
ParcelableTest(String author, String className) {
this.author = author;
this.className = className;
}
ParcelableTest(Parcel in) {
author = in.readString();
className = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(author);
dest.writeString(className);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<ParcelableTest> CREATOR = new Creator<ParcelableTest>() {
@Override
public ParcelableTest createFromParcel(Parcel in) {
return new ParcelableTest(in);
}
@Override
public ParcelableTest[] newArray(int size) {
return new ParcelableTest[size];
}
};
@Override
public boolean equals(Object obj) {
return obj instanceof ParcelableTest
&& ((ParcelableTest) obj).author.equals(author)
&& ((ParcelableTest) obj).className.equals(className);
}
}
static class SerializableTest implements Serializable {
private static final long serialVersionUID = -5806706668736895024L;
String author;
String className;
SerializableTest(String author, String className) {
this.author = author;
this.className = className;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
@Override
public boolean equals(Object obj) {
return obj instanceof SerializableTest
&& ((SerializableTest) obj).author.equals(author)
&& ((SerializableTest) obj).className.equals(className);
}
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/RegexUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/RegexUtilsTest.java | package com.blankj.utilcode.util;
import com.blankj.utilcode.constant.RegexConstants;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/08/16
* desc : test RegexUtils
* </pre>
*/
public class RegexUtilsTest extends BaseTest {
@Test
public void isMobileSimple() {
assertTrue(RegexUtils.isMobileSimple("11111111111"));
}
@Test
public void isMobileExact() {
assertFalse(RegexUtils.isMobileExact("11111111111"));
assertTrue(RegexUtils.isMobileExact("13888880000"));
assertTrue(RegexUtils.isMobileExact("12088880000", CollectionUtils.newArrayList("120")));
}
@Test
public void isTel() {
assertTrue(RegexUtils.isTel("033-88888888"));
assertTrue(RegexUtils.isTel("033-7777777"));
assertTrue(RegexUtils.isTel("0444-88888888"));
assertTrue(RegexUtils.isTel("0444-7777777"));
assertTrue(RegexUtils.isTel("033 88888888"));
assertTrue(RegexUtils.isTel("033 7777777"));
assertTrue(RegexUtils.isTel("0444 88888888"));
assertTrue(RegexUtils.isTel("0444 7777777"));
assertTrue(RegexUtils.isTel("03388888888"));
assertTrue(RegexUtils.isTel("0337777777"));
assertTrue(RegexUtils.isTel("044488888888"));
assertTrue(RegexUtils.isTel("04447777777"));
assertFalse(RegexUtils.isTel("133-88888888"));
assertFalse(RegexUtils.isTel("033-666666"));
assertFalse(RegexUtils.isTel("0444-999999999"));
}
@Test
public void isIDCard18() {
assertTrue(RegexUtils.isIDCard18("33698418400112523x"));
assertTrue(RegexUtils.isIDCard18("336984184001125233"));
assertFalse(RegexUtils.isIDCard18("336984184021125233"));
}
@Test
public void isIDCard18Exact() {
assertFalse(RegexUtils.isIDCard18Exact("33698418400112523x"));
assertTrue(RegexUtils.isIDCard18Exact("336984184001125233"));
assertFalse(RegexUtils.isIDCard18Exact("336984184021125233"));
}
@Test
public void isEmail() {
assertTrue(RegexUtils.isEmail("blankj@qq.com"));
assertFalse(RegexUtils.isEmail("blankj@qq"));
}
@Test
public void isURL() {
assertTrue(RegexUtils.isURL("http://blankj.com"));
assertFalse(RegexUtils.isURL("https:blank"));
}
@Test
public void isZh() {
assertTrue(RegexUtils.isZh("我"));
assertFalse(RegexUtils.isZh("wo"));
}
@Test
public void isUsername() {
assertTrue(RegexUtils.isUsername("小明233333"));
assertFalse(RegexUtils.isUsername("小明"));
assertFalse(RegexUtils.isUsername("小明233333_"));
}
@Test
public void isDate() {
assertTrue(RegexUtils.isDate("2016-08-16"));
assertTrue(RegexUtils.isDate("2016-02-29"));
assertFalse(RegexUtils.isDate("2015-02-29"));
assertFalse(RegexUtils.isDate("2016-8-16"));
}
@Test
public void isIP() {
assertTrue(RegexUtils.isIP("255.255.255.0"));
assertFalse(RegexUtils.isIP("256.255.255.0"));
}
@Test
public void isMatch() {
assertTrue(RegexUtils.isMatch("\\d?", "1"));
assertFalse(RegexUtils.isMatch("\\d?", "a"));
}
@Test
public void getMatches() {
// 贪婪
System.out.println(RegexUtils.getMatches("b.*j", "blankj blankj"));
// 懒惰
System.out.println(RegexUtils.getMatches("b.*?j", "blankj blankj"));
}
@Test
public void getSplits() {
System.out.println(Arrays.asList(RegexUtils.getSplits("1 2 3", " ")));
}
@Test
public void getReplaceFirst() {
System.out.println(RegexUtils.getReplaceFirst("1 2 3", " ", ", "));
}
@Test
public void getReplaceAll() {
System.out.println(RegexUtils.getReplaceAll("1 2 3", " ", ", "));
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/CloneUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/CloneUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Assert;
import org.junit.Test;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/04/08
* desc : test CloneUtils
* </pre>
*/
public class CloneUtilsTest extends BaseTest {
@Test
public void deepClone() {
Result<Person> result = new Result<>(new Person("Blankj"));
Result<Person> cloneResult = CloneUtils.deepClone(result, GsonUtils.getType(Result.class, Person.class));
System.out.println(result);
System.out.println(cloneResult);
Assert.assertNotEquals(result, cloneResult);
}
static class Result<T> {
int code;
String message;
T data;
Result(T data) {
this.code = 200;
this.message = "success";
this.data = data;
}
@Override
public String toString() {
return "{\"code\":" + primitive2String(code) +
",\"message\":" + primitive2String(message) +
",\"data\":" + primitive2String(data) + "}";
}
}
static class Person {
String name;
int gender;
String address;
Person(String name) {
this.name = name;
}
@Override
public String toString() {
return "{\"name\":" + primitive2String(name) +
",\"gender\":" + primitive2String(gender) +
",\"address\":" + primitive2String(address) + "}";
}
}
private static String primitive2String(final Object obj) {
if (obj == null) return "null";
if (obj instanceof CharSequence) return "\"" + obj.toString() + "\"";
return obj.toString();
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/ThreadUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/ThreadUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/05/21
* desc :
* </pre>
*/
public class ThreadUtilsTest extends BaseTest {
@Test
public void executeByFixed() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestTask<String> task = new TestTask<String>(latch) {
@Override
public String doInBackground() throws Throwable {
new ThreadGroup("name");
Thread.sleep(500 + index * 10);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeByFixed(3, task);
}
});
}
@Test
public void executeByFixedWithDelay() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestTask<String> task = new TestTask<String>(latch) {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(500);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeByFixedWithDelay(3, task, 500 + index * 10, TimeUnit.MILLISECONDS);
}
});
}
@Test
public void executeByFixedAtFixRate() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestScheduledTask<String> task = new TestScheduledTask<String>(latch, 3) {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(500 + index * 10);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeByFixedAtFixRate(3, task, 3000 + index * 10, TimeUnit.MILLISECONDS);
}
});
}
@Test
public void executeBySingle() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestTask<String> task = new TestTask<String>(latch) {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(200);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeBySingle(task);
}
});
}
@Test
public void executeBySingleWithDelay() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestTask<String> task = new TestTask<String>(latch) {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(500);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeBySingleWithDelay(task, 500 + index * 10, TimeUnit.MILLISECONDS);
}
});
}
@Test
public void executeBySingleAtFixRate() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestScheduledTask<String> task = new TestScheduledTask<String>(latch, 3) {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(100 + index * 10);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeBySingleAtFixRate(task, 2000 + index * 10, TimeUnit.MILLISECONDS);
}
});
}
@Test
public void executeByIo() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestTask<String> task = new TestTask<String>(latch) {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(500 + index * 10);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeByIo(task);
}
});
}
@Test
public void executeByIoWithDelay() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestTask<String> task = new TestTask<String>(latch) {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(500);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeByIoWithDelay(task, 500 + index * 10, TimeUnit.MILLISECONDS);
}
});
}
@Test
public void executeByIoAtFixRate() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestScheduledTask<String> task = new TestScheduledTask<String>(latch, 3) {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(100 + index * 10);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeByIoAtFixRate(task, 1000, TimeUnit.MILLISECONDS);
}
});
}
@Test
public void executeByCpu() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestTask<String> task = new TestTask<String>(latch) {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(500 + index * 10);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeByCpu(task);
}
});
}
@Test
public void executeByCpuWithDelay() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestTask<String> task = new TestTask<String>(latch) {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(500);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeByCpuWithDelay(task, 500 + index * 10, TimeUnit.MILLISECONDS);
}
});
}
@Test
public void executeByCpuAtFixRate() throws Exception {
asyncTest(10, new TestRunnable<String>() {
@Override
public void run(final int index, CountDownLatch latch) {
final TestScheduledTask<String> task = new TestScheduledTask<String>(latch, 3) {
@Override
public String doInBackground() throws Throwable {
Thread.sleep(100 + index * 10);
if (index < 4) {
return Thread.currentThread() + " :" + index;
} else if (index < 7) {
cancel();
return null;
} else {
throw new NullPointerException(String.valueOf(index));
}
}
@Override
void onTestSuccess(String result) {
System.out.println(result);
}
};
ThreadUtils.executeByCpuAtFixRate(task, 1000, TimeUnit.MILLISECONDS);
}
});
}
@Test
public void cancelPoolTask() throws InterruptedException {
int count = 300;
final CountDownLatch countDownLatch = new CountDownLatch(count);
for (int i = 0; i < count; i++) {
final int finalI = i;
ThreadUtils.executeByCached(new ThreadUtils.Task<Integer>() {
@Override
public Integer doInBackground() throws Throwable {
Thread.sleep(10 * finalI);
return finalI;
}
@Override
public void onSuccess(Integer result) {
System.out.println(result);
if (result == 10) {
ThreadUtils.cancel(ThreadUtils.getCachedPool());
}
countDownLatch.countDown();
}
@Override
public void onCancel() {
System.out.println("onCancel: " + finalI);
countDownLatch.countDown();
}
@Override
public void onFail(Throwable t) {
countDownLatch.countDown();
}
});
}
countDownLatch.await();
}
@Test
public void testTimeout() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
ThreadUtils.Task<Boolean> task = new ThreadUtils.SimpleTask<Boolean>() {
@Override
public Boolean doInBackground() throws Throwable {
System.out.println("doInBackground start");
Thread.sleep(2000);
System.out.println("doInBackground end");
return null;
}
@Override
public void onSuccess(Boolean result) {
System.out.println("onSuccess");
}
}.setTimeout(1000, new ThreadUtils.Task.OnTimeoutListener() {
@Override
public void onTimeout() {
System.out.println("onTimeout");
}
});
ThreadUtils.executeByCached(task);
latch.await(3, TimeUnit.SECONDS);
}
abstract static class TestScheduledTask<T> extends ThreadUtils.Task<T> {
private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();
private int mTimes;
CountDownLatch mLatch;
TestScheduledTask(final CountDownLatch latch, final int times) {
mLatch = latch;
mTimes = times;
}
abstract void onTestSuccess(T result);
@Override
public void onSuccess(T result) {
onTestSuccess(result);
if (ATOMIC_INTEGER.addAndGet(1) % mTimes == 0) {
mLatch.countDown();
}
}
@Override
public void onCancel() {
System.out.println(Thread.currentThread() + " onCancel: ");
mLatch.countDown();
}
@Override
public void onFail(Throwable t) {
System.out.println(Thread.currentThread() + " onFail: " + t);
mLatch.countDown();
}
}
abstract static class TestTask<T> extends ThreadUtils.Task<T> {
CountDownLatch mLatch;
TestTask(final CountDownLatch latch) {
mLatch = latch;
}
abstract void onTestSuccess(T result);
@Override
public void onSuccess(T result) {
onTestSuccess(result);
mLatch.countDown();
}
@Override
public void onCancel() {
System.out.println(Thread.currentThread() + " onCancel: ");
mLatch.countDown();
}
@Override
public void onFail(Throwable t) {
System.out.println(Thread.currentThread() + " onFail: " + t);
mLatch.countDown();
}
}
private <T> void asyncTest(int threadCount, TestRunnable<T> runnable) throws Exception {
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
runnable.run(i, latch);
}
latch.await();
}
interface TestRunnable<T> {
void run(final int index, CountDownLatch latch);
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/GsonUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/GsonUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/09/26
* desc : test GsonUtils
* </pre>
*/
public class GsonUtilsTest extends BaseTest {
@Test
public void getGson() {
Assert.assertNotNull(GsonUtils.getGson());
}
@Test
public void toJson() {
Result<Person> result = new Result<>(new Person("Blankj"));
Assert.assertEquals(
"{\"code\":200,\"message\":\"success\",\"data\":{\"name\":\"Blankj\",\"gender\":0,\"address\":null}}",
GsonUtils.toJson(result)
);
}
@Test
public void fromJson() {
List<Person> people = new ArrayList<>();
people.add(new Person("Blankj"));
people.add(new Person("Ming"));
Result<List<Person>> result = new Result<>(people);
Assert.assertEquals(
GsonUtils.toJson(result),
GsonUtils.toJson(
GsonUtils.fromJson(
GsonUtils.toJson(result),
GsonUtils.getType(Result.class, GsonUtils.getListType(Person.class))
)
)
);
}
@Test
public void getType() {
Assert.assertEquals(
"java.util.List<java.lang.String>",
GsonUtils.getListType(String.class).toString()
);
Assert.assertEquals(
"java.util.Map<java.lang.String, java.lang.Integer>",
GsonUtils.getMapType(String.class, Integer.class).toString()
);
Assert.assertEquals(
"java.lang.String[]",
GsonUtils.getArrayType(String.class).toString()
);
Assert.assertEquals(
"com.blankj.utilcode.util.GsonUtilsTest$Result<java.lang.String>",
GsonUtils.getType(Result.class, String.class).toString()
);
Assert.assertEquals(
"java.util.Map<java.lang.String, java.util.List<java.lang.String>>",
GsonUtils.getMapType(String.class, GsonUtils.getListType(String.class)).toString()
);
}
static class Result<T> {
int code;
String message;
T data;
Result(T data) {
this.code = 200;
this.message = "success";
this.data = data;
}
}
static class Person {
String name;
int gender;
String address;
Person(String name) {
this.name = name;
}
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDiskStaticUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDiskStaticUtilsTest.java | package com.blankj.utilcode.util;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.Serializable;
import static com.blankj.utilcode.util.TestConfig.FILE_SEP;
import static com.blankj.utilcode.util.TestConfig.PATH_CACHE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/01/04
* desc : test CacheDiskStaticUtils
* </pre>
*/
public class CacheDiskStaticUtilsTest extends BaseTest {
private static final String DISK1_PATH = PATH_CACHE + "disk1" + FILE_SEP;
private static final String DISK2_PATH = PATH_CACHE + "disk2" + FILE_SEP;
private static final File DISK1_FILE = new File(DISK1_PATH);
private static final File DISK2_FILE = new File(DISK2_PATH);
private static final CacheDiskUtils CACHE_DISK_UTILS1 = CacheDiskUtils.getInstance(DISK1_FILE);
private static final CacheDiskUtils CACHE_DISK_UTILS2 = CacheDiskUtils.getInstance(DISK2_FILE);
private static final byte[] BYTES = "CacheDiskUtils".getBytes();
private static final String STRING = "CacheDiskUtils";
private static final JSONObject JSON_OBJECT = new JSONObject();
private static final JSONArray JSON_ARRAY = new JSONArray();
private static final ParcelableTest PARCELABLE_TEST = new ParcelableTest("Blankj", "CacheDiskUtils");
private static final SerializableTest SERIALIZABLE_TEST = new SerializableTest("Blankj", "CacheDiskUtils");
private static final Bitmap BITMAP = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565);
private static final Drawable DRAWABLE = new BitmapDrawable(Utils.getApp().getResources(), BITMAP);
static {
try {
JSON_OBJECT.put("class", "CacheDiskUtils");
JSON_OBJECT.put("author", "Blankj");
JSON_ARRAY.put(0, JSON_OBJECT);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Before
public void setUp() {
CacheDiskStaticUtils.put("bytes1", BYTES, 60 * CacheDiskUtils.SEC, CACHE_DISK_UTILS1);
CacheDiskStaticUtils.put("string1", STRING, 60 * CacheDiskUtils.MIN, CACHE_DISK_UTILS1);
CacheDiskStaticUtils.put("jsonObject1", JSON_OBJECT, 24 * CacheDiskUtils.HOUR, CACHE_DISK_UTILS1);
CacheDiskStaticUtils.put("jsonArray1", JSON_ARRAY, 365 * CacheDiskUtils.DAY, CACHE_DISK_UTILS1);
CacheDiskStaticUtils.put("bitmap1", BITMAP, 60 * CacheDiskUtils.SEC, CACHE_DISK_UTILS1);
CacheDiskStaticUtils.put("drawable1", DRAWABLE, 60 * CacheDiskUtils.SEC, CACHE_DISK_UTILS1);
CacheDiskStaticUtils.put("parcelable1", PARCELABLE_TEST, 60 * CacheDiskUtils.SEC, CACHE_DISK_UTILS1);
CacheDiskStaticUtils.put("serializable1", SERIALIZABLE_TEST, 60 * CacheDiskUtils.SEC, CACHE_DISK_UTILS1);
CacheDiskStaticUtils.put("bytes2", BYTES, CACHE_DISK_UTILS2);
CacheDiskStaticUtils.put("string2", STRING, CACHE_DISK_UTILS2);
CacheDiskStaticUtils.put("jsonObject2", JSON_OBJECT, CACHE_DISK_UTILS2);
CacheDiskStaticUtils.put("jsonArray2", JSON_ARRAY, CACHE_DISK_UTILS2);
CacheDiskStaticUtils.put("bitmap2", BITMAP, CACHE_DISK_UTILS2);
CacheDiskStaticUtils.put("drawable2", DRAWABLE, CACHE_DISK_UTILS2);
CacheDiskStaticUtils.put("parcelable2", PARCELABLE_TEST, CACHE_DISK_UTILS2);
CacheDiskStaticUtils.put("serializable2", SERIALIZABLE_TEST, CACHE_DISK_UTILS2);
}
@Test
public void getBytes() {
assertEquals(STRING, new String(CacheDiskStaticUtils.getBytes("bytes1", CACHE_DISK_UTILS1)));
assertEquals(STRING, new String(CacheDiskStaticUtils.getBytes("bytes1", null, CACHE_DISK_UTILS1)));
assertNull(CacheDiskStaticUtils.getBytes("bytes2", null, CACHE_DISK_UTILS1));
assertEquals(STRING, new String(CacheDiskStaticUtils.getBytes("bytes2", CACHE_DISK_UTILS2)));
assertEquals(STRING, new String(CacheDiskStaticUtils.getBytes("bytes2", null, CACHE_DISK_UTILS2)));
assertNull(CacheDiskStaticUtils.getBytes("bytes1", null, CACHE_DISK_UTILS2));
}
@Test
public void getString() {
assertEquals(STRING, CacheDiskStaticUtils.getString("string1", CACHE_DISK_UTILS1));
assertEquals(STRING, CacheDiskStaticUtils.getString("string1", null, CACHE_DISK_UTILS1));
assertNull(CacheDiskStaticUtils.getString("string2", null, CACHE_DISK_UTILS1));
assertEquals(STRING, CacheDiskStaticUtils.getString("string2", CACHE_DISK_UTILS2));
assertEquals(STRING, CacheDiskStaticUtils.getString("string2", null, CACHE_DISK_UTILS2));
assertNull(CacheDiskStaticUtils.getString("string1", null, CACHE_DISK_UTILS2));
}
@Test
public void getJSONObject() {
assertEquals(JSON_OBJECT.toString(), CacheDiskStaticUtils.getJSONObject("jsonObject1", CACHE_DISK_UTILS1).toString());
assertEquals(JSON_OBJECT.toString(), CacheDiskStaticUtils.getJSONObject("jsonObject1", null, CACHE_DISK_UTILS1).toString());
assertNull(CacheDiskStaticUtils.getJSONObject("jsonObject2", null, CACHE_DISK_UTILS1));
assertEquals(JSON_OBJECT.toString(), CacheDiskStaticUtils.getJSONObject("jsonObject2", CACHE_DISK_UTILS2).toString());
assertEquals(JSON_OBJECT.toString(), CacheDiskStaticUtils.getJSONObject("jsonObject2", null, CACHE_DISK_UTILS2).toString());
assertNull(CacheDiskStaticUtils.getJSONObject("jsonObject1", null, CACHE_DISK_UTILS2));
}
@Test
public void getJSONArray() {
assertEquals(JSON_ARRAY.toString(), CacheDiskStaticUtils.getJSONArray("jsonArray1", CACHE_DISK_UTILS1).toString());
assertEquals(JSON_ARRAY.toString(), CacheDiskStaticUtils.getJSONArray("jsonArray1", null, CACHE_DISK_UTILS1).toString());
assertNull(CacheDiskStaticUtils.getJSONArray("jsonArray2", null, CACHE_DISK_UTILS1));
assertEquals(JSON_ARRAY.toString(), CacheDiskStaticUtils.getJSONArray("jsonArray2", CACHE_DISK_UTILS2).toString());
assertEquals(JSON_ARRAY.toString(), CacheDiskStaticUtils.getJSONArray("jsonArray2", null, CACHE_DISK_UTILS2).toString());
assertNull(CacheDiskStaticUtils.getJSONArray("jsonArray1", null, CACHE_DISK_UTILS2));
}
@Test
public void getBitmap() {
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.bitmap2Bytes(CacheDiskStaticUtils.getBitmap("bitmap1", CACHE_DISK_UTILS1), Bitmap.CompressFormat.PNG, 100)
);
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.bitmap2Bytes(CacheDiskStaticUtils.getBitmap("bitmap1", null, CACHE_DISK_UTILS1), Bitmap.CompressFormat.PNG, 100)
);
assertNull(CacheDiskStaticUtils.getBitmap("bitmap2", null, CACHE_DISK_UTILS1));
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.bitmap2Bytes(CacheDiskStaticUtils.getBitmap("bitmap2", CACHE_DISK_UTILS2), Bitmap.CompressFormat.PNG, 100)
);
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.bitmap2Bytes(CacheDiskStaticUtils.getBitmap("bitmap2", null, CACHE_DISK_UTILS2), Bitmap.CompressFormat.PNG, 100)
);
assertNull(CacheDiskStaticUtils.getBitmap("bitmap1", null, CACHE_DISK_UTILS2));
}
@Test
public void getDrawable() {
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.drawable2Bytes(CacheDiskStaticUtils.getDrawable("drawable1", CACHE_DISK_UTILS1), Bitmap.CompressFormat.PNG, 100)
);
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.drawable2Bytes(CacheDiskStaticUtils.getDrawable("drawable1", null, CACHE_DISK_UTILS1), Bitmap.CompressFormat.PNG, 100)
);
assertNull(CacheDiskStaticUtils.getDrawable("drawable2", null, CACHE_DISK_UTILS1));
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.drawable2Bytes(CacheDiskStaticUtils.getDrawable("drawable2", CACHE_DISK_UTILS2), Bitmap.CompressFormat.PNG, 100)
);
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.drawable2Bytes(CacheDiskStaticUtils.getDrawable("drawable2", null, CACHE_DISK_UTILS2), Bitmap.CompressFormat.PNG, 100)
);
assertNull(CacheDiskStaticUtils.getDrawable("drawable1", null, CACHE_DISK_UTILS2));
}
@Test
public void getParcel() {
assertEquals(PARCELABLE_TEST, CacheDiskStaticUtils.getParcelable("parcelable1", ParcelableTest.CREATOR, CACHE_DISK_UTILS1));
assertEquals(PARCELABLE_TEST, CacheDiskStaticUtils.getParcelable("parcelable1", ParcelableTest.CREATOR, null, CACHE_DISK_UTILS1));
assertNull(CacheDiskStaticUtils.getParcelable("parcelable2", ParcelableTest.CREATOR, null, CACHE_DISK_UTILS1));
assertEquals(PARCELABLE_TEST, CacheDiskStaticUtils.getParcelable("parcelable2", ParcelableTest.CREATOR, CACHE_DISK_UTILS2));
assertEquals(PARCELABLE_TEST, CacheDiskStaticUtils.getParcelable("parcelable2", ParcelableTest.CREATOR, null, CACHE_DISK_UTILS2));
assertNull(CacheDiskStaticUtils.getParcelable("parcelable1", ParcelableTest.CREATOR, null, CACHE_DISK_UTILS2));
}
@Test
public void getSerializable() {
assertEquals(SERIALIZABLE_TEST, CacheDiskStaticUtils.getSerializable("serializable1", CACHE_DISK_UTILS1));
assertEquals(SERIALIZABLE_TEST, CacheDiskStaticUtils.getSerializable("serializable1", null, CACHE_DISK_UTILS1));
assertNull(CacheDiskStaticUtils.getSerializable("parcelable2", null, CACHE_DISK_UTILS1));
assertEquals(SERIALIZABLE_TEST, CacheDiskStaticUtils.getSerializable("serializable2", CACHE_DISK_UTILS2));
assertEquals(SERIALIZABLE_TEST, CacheDiskStaticUtils.getSerializable("serializable2", null, CACHE_DISK_UTILS2));
assertNull(CacheDiskStaticUtils.getSerializable("parcelable1", null, CACHE_DISK_UTILS2));
}
@Test
public void getCacheSize() {
assertEquals(FileUtils.getLength(DISK1_FILE), CacheDiskStaticUtils.getCacheSize(CACHE_DISK_UTILS1));
assertEquals(FileUtils.getLength(DISK2_FILE), CacheDiskStaticUtils.getCacheSize(CACHE_DISK_UTILS2));
}
@Test
public void getCacheCount() {
assertEquals(8, CacheDiskStaticUtils.getCacheCount(CACHE_DISK_UTILS1));
assertEquals(8, CacheDiskStaticUtils.getCacheCount(CACHE_DISK_UTILS2));
}
@Test
public void remove() {
assertNotNull(CacheDiskStaticUtils.getString("string1", CACHE_DISK_UTILS1));
CacheDiskStaticUtils.remove("string1", CACHE_DISK_UTILS1);
assertNull(CacheDiskStaticUtils.getString("string1", CACHE_DISK_UTILS1));
assertNotNull(CacheDiskStaticUtils.getString("string2", CACHE_DISK_UTILS2));
CacheDiskStaticUtils.remove("string2", CACHE_DISK_UTILS2);
assertNull(CacheDiskStaticUtils.getString("string2", CACHE_DISK_UTILS2));
}
@Test
public void clear() {
assertNotNull(CacheDiskStaticUtils.getBytes("bytes1", CACHE_DISK_UTILS1));
assertNotNull(CacheDiskStaticUtils.getString("string1", CACHE_DISK_UTILS1));
assertNotNull(CacheDiskStaticUtils.getJSONObject("jsonObject1", CACHE_DISK_UTILS1));
assertNotNull(CacheDiskStaticUtils.getJSONArray("jsonArray1", CACHE_DISK_UTILS1));
assertNotNull(CacheDiskStaticUtils.getBitmap("bitmap1", CACHE_DISK_UTILS1));
assertNotNull(CacheDiskStaticUtils.getDrawable("drawable1", CACHE_DISK_UTILS1));
assertNotNull(CacheDiskStaticUtils.getParcelable("parcelable1", ParcelableTest.CREATOR, CACHE_DISK_UTILS1));
assertNotNull(CacheDiskStaticUtils.getSerializable("serializable1", CACHE_DISK_UTILS1));
CacheDiskStaticUtils.clear(CACHE_DISK_UTILS1);
assertNull(CacheDiskStaticUtils.getBytes("bytes1", CACHE_DISK_UTILS1));
assertNull(CacheDiskStaticUtils.getString("string1", CACHE_DISK_UTILS1));
assertNull(CacheDiskStaticUtils.getJSONObject("jsonObject1", CACHE_DISK_UTILS1));
assertNull(CacheDiskStaticUtils.getJSONArray("jsonArray1", CACHE_DISK_UTILS1));
assertNull(CacheDiskStaticUtils.getBitmap("bitmap1", CACHE_DISK_UTILS1));
assertNull(CacheDiskStaticUtils.getDrawable("drawable1", CACHE_DISK_UTILS1));
assertNull(CacheDiskStaticUtils.getParcelable("parcelable1", ParcelableTest.CREATOR, CACHE_DISK_UTILS1));
assertNull(CacheDiskStaticUtils.getSerializable("serializable1", CACHE_DISK_UTILS1));
assertEquals(0, CacheDiskStaticUtils.getCacheSize(CACHE_DISK_UTILS1));
assertEquals(0, CacheDiskStaticUtils.getCacheCount(CACHE_DISK_UTILS1));
assertNotNull(CacheDiskStaticUtils.getBytes("bytes2", CACHE_DISK_UTILS2));
assertNotNull(CacheDiskStaticUtils.getString("string2", CACHE_DISK_UTILS2));
assertNotNull(CacheDiskStaticUtils.getJSONObject("jsonObject2", CACHE_DISK_UTILS2));
assertNotNull(CacheDiskStaticUtils.getJSONArray("jsonArray2", CACHE_DISK_UTILS2));
assertNotNull(CacheDiskStaticUtils.getBitmap("bitmap2", CACHE_DISK_UTILS2));
assertNotNull(CacheDiskStaticUtils.getDrawable("drawable2", CACHE_DISK_UTILS2));
assertNotNull(CacheDiskStaticUtils.getParcelable("parcelable2", ParcelableTest.CREATOR, CACHE_DISK_UTILS2));
assertNotNull(CacheDiskStaticUtils.getSerializable("serializable2", CACHE_DISK_UTILS2));
CacheDiskStaticUtils.clear(CACHE_DISK_UTILS2);
assertNull(CacheDiskStaticUtils.getBytes("bytes2", CACHE_DISK_UTILS2));
assertNull(CacheDiskStaticUtils.getString("string2", CACHE_DISK_UTILS2));
assertNull(CacheDiskStaticUtils.getJSONObject("jsonObject2", CACHE_DISK_UTILS2));
assertNull(CacheDiskStaticUtils.getJSONArray("jsonArray2", CACHE_DISK_UTILS2));
assertNull(CacheDiskStaticUtils.getBitmap("bitmap2", CACHE_DISK_UTILS2));
assertNull(CacheDiskStaticUtils.getDrawable("drawable2", CACHE_DISK_UTILS2));
assertNull(CacheDiskStaticUtils.getParcelable("parcelable2", ParcelableTest.CREATOR, CACHE_DISK_UTILS2));
assertNull(CacheDiskStaticUtils.getSerializable("serializable2", CACHE_DISK_UTILS2));
assertEquals(0, CacheDiskStaticUtils.getCacheSize(CACHE_DISK_UTILS2));
assertEquals(0, CacheDiskStaticUtils.getCacheCount(CACHE_DISK_UTILS2));
}
@After
public void tearDown() {
CacheDiskStaticUtils.clear(CACHE_DISK_UTILS1);
CacheDiskStaticUtils.clear(CACHE_DISK_UTILS2);
}
static class ParcelableTest implements Parcelable {
String author;
String className;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
ParcelableTest(String author, String className) {
this.author = author;
this.className = className;
}
ParcelableTest(Parcel in) {
author = in.readString();
className = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(author);
dest.writeString(className);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<ParcelableTest> CREATOR = new Creator<ParcelableTest>() {
@Override
public ParcelableTest createFromParcel(Parcel in) {
return new ParcelableTest(in);
}
@Override
public ParcelableTest[] newArray(int size) {
return new ParcelableTest[size];
}
};
@Override
public boolean equals(Object obj) {
return obj instanceof ParcelableTest
&& ((ParcelableTest) obj).author.equals(author)
&& ((ParcelableTest) obj).className.equals(className);
}
}
static class SerializableTest implements Serializable {
private static final long serialVersionUID = -5806706668736895024L;
String author;
String className;
SerializableTest(String author, String className) {
this.author = author;
this.className = className;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
@Override
public boolean equals(Object obj) {
return obj instanceof SerializableTest
&& ((SerializableTest) obj).author.equals(author)
&& ((SerializableTest) obj).className.equals(className);
}
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/MapUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/MapUtilsTest.java | package com.blankj.utilcode.util;
import android.util.Pair;
import org.junit.Assert;
import org.junit.Test;
import java.util.Comparator;
import java.util.Map;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/08/14
* desc : test MapUtils
* </pre>
*/
public class MapUtilsTest extends BaseTest {
@Test
public void newUnmodifiableMap() {
System.out.println(MapUtils.newUnmodifiableMap(
Pair.create(0, "0"),
Pair.create(1, "1"),
Pair.create(2, "2"),
Pair.create(3, "3")
));
}
@Test
public void newHashMap() {
System.out.println(MapUtils.newHashMap(
Pair.create(0, "0"),
Pair.create(1, "1"),
Pair.create(2, "2"),
Pair.create(3, "3")
));
}
@Test
public void newLinkedHashMap() {
System.out.println(MapUtils.newLinkedHashMap(
Pair.create(0, "0"),
Pair.create(1, "1"),
Pair.create(2, "2"),
Pair.create(3, "3")
));
}
@Test
public void newTreeMap() {
System.out.println(MapUtils.newTreeMap(
new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
},
Pair.create(0, "0"),
Pair.create(1, "1"),
Pair.create(2, "2"),
Pair.create(3, "3")
));
}
@Test
public void newHashTable() {
System.out.println(MapUtils.newHashTable(
Pair.create(0, "0"),
Pair.create(1, "1"),
Pair.create(2, "2"),
Pair.create(3, "3")
));
}
@Test
public void isEmpty() {
Assert.assertTrue(MapUtils.isEmpty(null));
Assert.assertTrue(MapUtils.isEmpty(MapUtils.newHashMap()));
Assert.assertFalse(MapUtils.isEmpty(MapUtils.newHashMap(Pair.create(0, 0))));
}
@Test
public void isNotEmpty() {
Assert.assertFalse(MapUtils.isNotEmpty(null));
Assert.assertFalse(MapUtils.isNotEmpty(MapUtils.newHashMap()));
Assert.assertTrue(MapUtils.isNotEmpty(MapUtils.newHashMap(Pair.create(0, 0))));
}
@Test
public void size() {
Assert.assertEquals(0, MapUtils.size(null));
Assert.assertEquals(0, MapUtils.size(MapUtils.newHashMap()));
Assert.assertEquals(1, MapUtils.size(MapUtils.newHashMap(Pair.create(0, 0))));
}
@Test
public void forAllDo() {
MapUtils.forAllDo(
MapUtils.newHashMap(
Pair.create(0, "0"),
Pair.create(1, "1"),
Pair.create(2, "2"),
Pair.create(3, "3")
), new MapUtils.Closure<Integer, String>() {
@Override
public void execute(Integer key, String value) {
System.out.println(key + "=" + value);
}
});
}
@Test
public void transform() {
Map<String, String> transform = MapUtils.transform(
MapUtils.newHashMap(
Pair.create(0, "0"),
Pair.create(1, "1"),
Pair.create(2, "2"),
Pair.create(3, "3")
),
new MapUtils.Transformer<Integer, String, String, String>() {
@Override
public Pair<String, String> transform(Integer integer, String s) {
return Pair.create("StringKey" + integer, s);
}
}
);
System.out.println(transform);
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/BusUtilsVsEventBusTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/BusUtilsVsEventBusTest.java | package com.blankj.utilcode.util;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/07/14
* desc :
* </pre>
*/
public class BusUtilsVsEventBusTest extends BaseTest {
@Subscribe
public void eventBusFun(String param) {
}
@BusUtils.Bus(tag = "busUtilsFun")
public void busUtilsFun(String param) {
}
@Before
public void setUp() throws Exception {
// 这一步是在 AOP 的时候注入的,这里通过反射来注入 busUtilsFun 事件,效果是一样的
ReflectUtils getInstance = ReflectUtils.reflect(BusUtils.class).method("getInstance");
getInstance.method("registerBus", "busUtilsFun", BusUtilsVsEventBusTest.class.getName(), "busUtilsFun", String.class.getName(), "param", false, "POSTING");
}
/**
* 注册 10000 个订阅者,共执行 10 次取平均值
*/
// @Test
public void compareRegister10000Times() {
final List<BusUtilsVsEventBusTest> eventBusTests = new ArrayList<>();
final List<BusUtilsVsEventBusTest> busUtilsTests = new ArrayList<>();
compareWithEventBus("Register 10000 times.", 10, 10000, new CompareCallback() {
@Override
public void runEventBus() {
BusUtilsVsEventBusTest test = new BusUtilsVsEventBusTest();
EventBus.getDefault().register(test);
eventBusTests.add(test);
}
@Override
public void runBusUtils() {
BusUtilsVsEventBusTest test = new BusUtilsVsEventBusTest();
BusUtils.register(test);
busUtilsTests.add(test);
}
@Override
public void restState() {
for (BusUtilsVsEventBusTest test : eventBusTests) {
EventBus.getDefault().unregister(test);
}
eventBusTests.clear();
for (BusUtilsVsEventBusTest test : busUtilsTests) {
BusUtils.unregister(test);
}
busUtilsTests.clear();
}
});
}
/**
* 向 1 个订阅者发送 * 1000000 次,共执行 10 次取平均值
*/
// @Test
public void comparePostTo1Subscriber1000000Times() {
comparePostTemplate("Post to 1 subscriber 1000000 times.", 1, 1000000);
}
/**
* 向 100 个订阅者发送 * 100000 次,共执行 10 次取平均值
*/
// @Test
public void comparePostTo100Subscribers100000Times() {
comparePostTemplate("Post to 100 subscribers 100000 times.", 100, 100000);
}
private void comparePostTemplate(String name, int subscribeNum, int postTimes) {
final List<BusUtilsVsEventBusTest> tests = new ArrayList<>();
for (int i = 0; i < subscribeNum; i++) {
BusUtilsVsEventBusTest test = new BusUtilsVsEventBusTest();
EventBus.getDefault().register(test);
BusUtils.register(test);
tests.add(test);
}
compareWithEventBus(name, 10, postTimes, new CompareCallback() {
@Override
public void runEventBus() {
EventBus.getDefault().post("EventBus");
}
@Override
public void runBusUtils() {
BusUtils.post("busUtilsFun", "BusUtils");
}
@Override
public void restState() {
}
});
for (BusUtilsVsEventBusTest test : tests) {
EventBus.getDefault().unregister(test);
BusUtils.unregister(test);
}
}
/**
* 注销 10000 个订阅者,共执行 10 次取平均值
*/
// @Test
public void compareUnregister10000Times() {
final List<BusUtilsVsEventBusTest> tests = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
BusUtilsVsEventBusTest test = new BusUtilsVsEventBusTest();
EventBus.getDefault().register(test);
BusUtils.register(test);
tests.add(test);
}
compareWithEventBus("Unregister 10000 times.", 10, 1, new CompareCallback() {
@Override
public void runEventBus() {
for (BusUtilsVsEventBusTest test : tests) {
EventBus.getDefault().unregister(test);
}
}
@Override
public void runBusUtils() {
for (BusUtilsVsEventBusTest test : tests) {
BusUtils.unregister(test);
}
}
@Override
public void restState() {
for (BusUtilsVsEventBusTest test : tests) {
EventBus.getDefault().register(test);
BusUtils.register(test);
}
}
});
for (BusUtilsVsEventBusTest test : tests) {
EventBus.getDefault().unregister(test);
BusUtils.unregister(test);
}
}
/**
* @param name 传入的测试函数名
* @param sampleSize 样本的数量
* @param times 每次执行的次数
* @param callback 比较的回调函数
*/
private void compareWithEventBus(String name, int sampleSize, int times, CompareCallback callback) {
long[][] dur = new long[2][sampleSize];
for (int i = 0; i < sampleSize; i++) {
long cur = System.currentTimeMillis();
for (int j = 0; j < times; j++) {
callback.runEventBus();
}
dur[0][i] = System.currentTimeMillis() - cur;
cur = System.currentTimeMillis();
for (int j = 0; j < times; j++) {
callback.runBusUtils();
}
dur[1][i] = System.currentTimeMillis() - cur;
callback.restState();
}
long eventBusAverageTime = 0;
long busUtilsAverageTime = 0;
for (int i = 0; i < sampleSize; i++) {
eventBusAverageTime += dur[0][i];
busUtilsAverageTime += dur[1][i];
}
System.out.println(
name +
"\nEventBusCostTime: " + eventBusAverageTime / sampleSize +
"\nBusUtilsCostTime: " + busUtilsAverageTime / sampleSize
);
}
public interface CompareCallback {
void runEventBus();
void runBusUtils();
void restState();
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/FileUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/FileUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Test;
import java.io.File;
import java.io.FileFilter;
import static com.blankj.utilcode.util.TestConfig.FILE_SEP;
import static com.blankj.utilcode.util.TestConfig.PATH_FILE;
import static com.blankj.utilcode.util.TestConfig.PATH_TEMP;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/08/19
* desc : test FileUtils
* </pre>
*/
public class FileUtilsTest extends BaseTest {
private FileFilter mFilter = new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith("8.txt");
}
};
private FileUtils.OnReplaceListener mListener = new FileUtils.OnReplaceListener() {
@Override
public boolean onReplace(File srcFile, File destFile) {
return true;
}
};
@Test
public void getFileByPath() {
assertNull(FileUtils.getFileByPath(" "));
assertNotNull(FileUtils.getFileByPath(PATH_FILE));
}
@Test
public void isFileExists() {
assertTrue(FileUtils.isFileExists(PATH_FILE + "UTF8.txt"));
assertFalse(FileUtils.isFileExists(PATH_FILE + "UTF8"));
}
@Test
public void rename() {
assertTrue(FileUtils.rename(PATH_FILE + "GBK.txt", "GBK1.txt"));
assertTrue(FileUtils.rename(PATH_FILE + "GBK1.txt", "GBK.txt"));
}
@Test
public void isDir() {
assertFalse(FileUtils.isDir(PATH_FILE + "UTF8.txt"));
assertTrue(FileUtils.isDir(PATH_FILE));
}
@Test
public void isFile() {
assertTrue(FileUtils.isFile(PATH_FILE + "UTF8.txt"));
assertFalse(FileUtils.isFile(PATH_FILE));
}
@Test
public void createOrExistsDir() {
assertTrue(FileUtils.createOrExistsDir(PATH_FILE + "new Dir"));
assertTrue(FileUtils.createOrExistsDir(PATH_FILE));
assertTrue(FileUtils.delete(PATH_FILE + "new Dir"));
}
@Test
public void createOrExistsFile() {
assertTrue(FileUtils.createOrExistsFile(PATH_FILE + "new File"));
assertFalse(FileUtils.createOrExistsFile(PATH_FILE));
assertTrue(FileUtils.delete(PATH_FILE + "new File"));
}
@Test
public void createFileByDeleteOldFile() {
assertTrue(FileUtils.createFileByDeleteOldFile(PATH_FILE + "new File"));
assertFalse(FileUtils.createFileByDeleteOldFile(PATH_FILE));
assertTrue(FileUtils.delete(PATH_FILE + "new File"));
}
@Test
public void copyDir() {
assertFalse(FileUtils.copy(PATH_FILE, PATH_FILE, mListener));
assertFalse(FileUtils.copy(PATH_FILE, PATH_FILE + "new Dir", mListener));
assertTrue(FileUtils.copy(PATH_FILE, PATH_TEMP, mListener));
assertTrue(FileUtils.delete(PATH_TEMP));
}
@Test
public void copyFile() {
assertFalse(FileUtils.copy(PATH_FILE + "GBK.txt", PATH_FILE + "GBK.txt", mListener));
assertTrue(FileUtils.copy(PATH_FILE + "GBK.txt", PATH_FILE + "new Dir" + FILE_SEP + "GBK.txt", mListener));
assertTrue(FileUtils.copy(PATH_FILE + "GBK.txt", PATH_TEMP + "GBK.txt", mListener));
assertTrue(FileUtils.delete(PATH_FILE + "new Dir"));
assertTrue(FileUtils.delete(PATH_TEMP));
}
@Test
public void moveDir() {
assertFalse(FileUtils.move(PATH_FILE, PATH_FILE, mListener));
assertFalse(FileUtils.move(PATH_FILE, PATH_FILE + "new Dir", mListener));
assertTrue(FileUtils.move(PATH_FILE, PATH_TEMP, mListener));
assertTrue(FileUtils.move(PATH_TEMP, PATH_FILE, mListener));
}
@Test
public void moveFile() {
assertFalse(FileUtils.move(PATH_FILE + "GBK.txt", PATH_FILE + "GBK.txt", mListener));
assertTrue(FileUtils.move(PATH_FILE + "GBK.txt", PATH_TEMP + "GBK.txt", mListener));
assertTrue(FileUtils.move(PATH_TEMP + "GBK.txt", PATH_FILE + "GBK.txt", mListener));
FileUtils.delete(PATH_TEMP);
}
@Test
public void listFilesInDir() {
System.out.println(FileUtils.listFilesInDir(PATH_FILE, false).toString());
System.out.println(FileUtils.listFilesInDir(PATH_FILE, true).toString());
}
@Test
public void listFilesInDirWithFilter() {
System.out.println(FileUtils.listFilesInDirWithFilter(PATH_FILE, mFilter, false).toString());
System.out.println(FileUtils.listFilesInDirWithFilter(PATH_FILE, mFilter, true).toString());
}
@Test
public void getFileLastModified() {
System.out.println(TimeUtils.millis2String(FileUtils.getFileLastModified(PATH_FILE)));
}
@Test
public void getFileCharsetSimple() {
assertEquals("GBK", FileUtils.getFileCharsetSimple(PATH_FILE + "GBK.txt"));
assertEquals("Unicode", FileUtils.getFileCharsetSimple(PATH_FILE + "Unicode.txt"));
assertEquals("UTF-8", FileUtils.getFileCharsetSimple(PATH_FILE + "UTF8.txt"));
assertEquals("UTF-16BE", FileUtils.getFileCharsetSimple(PATH_FILE + "UTF16BE.txt"));
}
@Test
public void isUtf8() {
assertTrue(FileUtils.isUtf8(PATH_FILE + "UTF8.txt"));
assertFalse(FileUtils.isUtf8(PATH_FILE + "UTF16BE.txt"));
assertFalse(FileUtils.isUtf8(PATH_FILE + "Unicode.txt"));
}
@Test
public void getFileLines() {
assertEquals(7, FileUtils.getFileLines(PATH_FILE + "UTF8.txt"));
}
@Test
public void getDirSize() {
System.out.println(FileUtils.getSize(PATH_FILE));
}
@Test
public void getFileSize() {
System.out.println(FileUtils.getSize(PATH_FILE + "UTF8.txt"));
}
@Test
public void getDirLength() {
System.out.println(FileUtils.getLength(PATH_FILE));
}
@Test
public void getFileLength() {
System.out.println(FileUtils.getFileLength(PATH_FILE + "UTF8.txt"));
// System.out.println(FileUtils.getFileLength("https://raw.githubusercontent.com/Blankj/AndroidUtilCode/85bc44d1c8adb31027870ea4cb7a931700c80cad/LICENSE"));
}
@Test
public void getFileMD5ToString() {
assertEquals("249D3E76851DCC56C945994DE9DAC406", FileUtils.getFileMD5ToString(PATH_FILE + "UTF8.txt"));
}
@Test
public void getDirName() {
assertEquals(PATH_FILE, FileUtils.getDirName(new File(PATH_FILE + "UTF8.txt")));
assertEquals(PATH_FILE, FileUtils.getDirName(PATH_FILE + "UTF8.txt"));
}
@Test
public void getFileName() {
assertEquals("UTF8.txt", FileUtils.getFileName(PATH_FILE + "UTF8.txt"));
assertEquals("UTF8.txt", FileUtils.getFileName(new File(PATH_FILE + "UTF8.txt")));
}
@Test
public void getFileNameNoExtension() {
assertEquals("UTF8", FileUtils.getFileNameNoExtension(PATH_FILE + "UTF8.txt"));
assertEquals("UTF8", FileUtils.getFileNameNoExtension(new File(PATH_FILE + "UTF8.txt")));
}
@Test
public void getFileExtension() {
assertEquals("txt", FileUtils.getFileExtension(new File(PATH_FILE + "UTF8.txt")));
assertEquals("txt", FileUtils.getFileExtension(PATH_FILE + "UTF8.txt"));
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/LogUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/LogUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/09/26
* desc : test LogUtils
* </pre>
*/
public class LogUtilsTest extends BaseTest {
private static final String JSON = "\r\n{\"tools\": [{ \"name\":\"css format\" , \"site\":\"http://tools.w3cschool.cn/code/css\" },{ \"name\":\"JSON format\" , \"site\":\"http://tools.w3cschool.cn/code/JSON\" },{ \"name\":\"pwd check\" , \"site\":\"http://tools.w3cschool.cn/password/my_password_safe\" }]}";
private static final String XML = "<books><book><author>Jack Herrington</author><title>PHP Hacks</title><publisher>O'Reilly</publisher></book><book><author>Jack Herrington</author><title>Podcasting Hacks</title><publisher>O'Reilly</publisher></book></books>";
private static final int[] ONE_D_ARRAY = new int[]{1, 2, 3};
private static final int[][] TWO_D_ARRAY = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
private static final ArrayList<String> LIST = new ArrayList<>();
private static final Map<String, Object> MAP = new HashMap<>();
@Test
public void testV() {
LogUtils.v();
LogUtils.v("");
LogUtils.v((Object) null);
LogUtils.v("hello");
LogUtils.v("hello\nworld");
LogUtils.v("hello", "world");
}
@Test
public void testVTag() {
LogUtils.vTag("");
LogUtils.vTag("", "");
LogUtils.vTag("TAG", (Object) null);
LogUtils.vTag("TAG", "hello");
LogUtils.vTag("TAG", "hello\nworld");
LogUtils.vTag("TAG", "hello", "world");
}
@Test
public void testD() {
LogUtils.d();
LogUtils.d("");
LogUtils.d((Object) null);
LogUtils.d("hello");
LogUtils.d("hello\nworld");
LogUtils.d("hello", "world");
}
@Test
public void testDTag() {
LogUtils.dTag("");
LogUtils.dTag("", "");
LogUtils.dTag("TAG", (Object) null);
LogUtils.dTag("TAG", "hello");
LogUtils.dTag("TAG", "hello\nworld");
LogUtils.dTag("TAG", "hello", "world");
}
@Test
public void testI() {
LogUtils.i();
LogUtils.i("");
LogUtils.i((Object) null);
LogUtils.i("hello");
LogUtils.i("hello\nworld");
LogUtils.i("hello", "world");
}
@Test
public void testITag() {
LogUtils.iTag("");
LogUtils.iTag("", "");
LogUtils.iTag("TAG", (Object) null);
LogUtils.iTag("TAG", "hello");
LogUtils.iTag("TAG", "hello\nworld");
LogUtils.iTag("TAG", "hello", "world");
}
@Test
public void testW() {
LogUtils.w();
LogUtils.w("");
LogUtils.w((Object) null);
LogUtils.w("hello");
LogUtils.w("hello\nworld");
LogUtils.w("hello", "world");
}
@Test
public void testWTag() {
LogUtils.wTag("");
LogUtils.wTag("", "");
LogUtils.wTag("TAG", (Object) null);
LogUtils.wTag("TAG", "hello");
LogUtils.wTag("TAG", "hello\nworld");
LogUtils.wTag("TAG", "hello", "world");
}
@Test
public void testE() {
LogUtils.e();
LogUtils.e("");
LogUtils.e((Object) null);
LogUtils.e("hello");
LogUtils.e("hello\nworld");
LogUtils.e("hello", "world");
}
@Test
public void testETag() {
LogUtils.eTag("");
LogUtils.eTag("", "");
LogUtils.eTag("TAG", (Object) null);
LogUtils.eTag("TAG", "hello");
LogUtils.eTag("TAG", "hello\nworld");
LogUtils.eTag("TAG", "hello", "world");
}
@Test
public void testA() {
LogUtils.a();
LogUtils.a("");
LogUtils.a((Object) null);
LogUtils.a("hello");
LogUtils.a("hello\nworld");
LogUtils.a("hello", "world");
}
@Test
public void testATag() {
LogUtils.aTag("");
LogUtils.aTag("", "");
LogUtils.aTag("TAG", (Object) null);
LogUtils.aTag("TAG", "hello");
LogUtils.aTag("TAG", "hello\nworld");
LogUtils.aTag("TAG", "hello", "world");
}
@Test
public void testJson() {
LogUtils.json(JSON);
LogUtils.json(new Person("Blankj"));
}
@Test
public void testXml() {
LogUtils.xml(XML);
}
@Test
public void testObject() {
LIST.add("hello");
LIST.add("log");
LIST.add("utils");
MAP.put("name", "AndroidUtilCode");
MAP.put("class", "LogUtils");
LogUtils.d((Object) ONE_D_ARRAY);
LogUtils.d((Object) TWO_D_ARRAY);
LogUtils.d(LIST);
LogUtils.d(MAP);
}
static class Person {
String name;
int gender;
String address;
public Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Person)) return false;
Person p = (Person) obj;
return equals(name, p.name) && p.gender == gender && equals(address, p.address);
}
private static boolean equals(final Object o1, final Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@Override
public String toString() {
return "{\"name\":" + primitive2String(name) +
",\"gender\":" + primitive2String(gender) +
",\"address\":" + primitive2String(address) + "}";
}
}
private static String primitive2String(final Object obj) {
if (obj == null) return "null";
if (obj instanceof CharSequence) return "\"" + obj.toString() + "\"";
return obj.toString();
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/ApiUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/ApiUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Before;
import org.junit.Test;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/11
* desc :
* </pre>
*/
public class ApiUtilsTest extends BaseTest {
@Before
public void setUp() throws Exception {
ApiUtils.register(TestApiImpl.class);
}
@Test
public void getApi() {
System.out.println("ApiUtils.getApi(TestApi.class).test(\"hehe\") = " + ApiUtils.getApi(TestApi.class).test("hehe"));
}
@Test
public void toString_() {
System.out.println("ApiUtils.toString_() = " + ApiUtils.toString_());
}
@ApiUtils.Api
public static class TestApiImpl extends TestApi {
@Override
public String test(String param) {
System.out.println("param = " + param);
return "haha";
}
}
public static abstract class TestApi extends ApiUtils.BaseApi {
public abstract String test(String name);
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/ArrayUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/ArrayUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/08/12
* desc : test ArrayUtils
* </pre>
*/
public class ArrayUtilsTest extends BaseTest {
@Test
public void newArray() {
// System.out.println(ArrayUtils.toString(ArrayUtils.newArray(null)));
System.out.println(ArrayUtils.toString(ArrayUtils.newArray((String) null)));
System.out.println(ArrayUtils.toString(ArrayUtils.newArray(0, 1, 2, 3)));
System.out.println(ArrayUtils.toString(ArrayUtils.newLongArray(0, 1, 2, 3)));
System.out.println(ArrayUtils.toString(ArrayUtils.newIntArray(0, 1, 2, 3)));
System.out.println(ArrayUtils.toString(ArrayUtils.newShortArray((short) 0, (short) 1, (short) 2, (short) 3)));
System.out.println(ArrayUtils.toString(ArrayUtils.newCharArray('0', '1', '2', '3')));
System.out.println(ArrayUtils.toString(ArrayUtils.newByteArray((byte) 0, (byte) 1, (byte) 2, (byte) 3)));
System.out.println(ArrayUtils.toString(ArrayUtils.newDoubleArray(0, 1, 2, 3)));
System.out.println(ArrayUtils.toString(ArrayUtils.newFloatArray(0, 1, 2, 3)));
System.out.println(ArrayUtils.toString(ArrayUtils.newBooleanArray(false, true, false, true)));
}
@Test
public void isEmpty() {
Object nullArr = null;
Object emptyArr = new int[]{};
Assert.assertTrue(ArrayUtils.isEmpty(nullArr));
Assert.assertTrue(ArrayUtils.isEmpty(emptyArr));
Assert.assertFalse(ArrayUtils.isEmpty(new int[]{1}));
}
@Test
public void getLength() {
Object nullArr = null;
Object emptyArr = new int[]{};
Assert.assertEquals(0, ArrayUtils.getLength(nullArr));
Assert.assertEquals(0, ArrayUtils.getLength(emptyArr));
Assert.assertEquals(1, ArrayUtils.getLength(new int[]{1}));
}
@Test
public void isSameLength() {
Object emptyArr1 = new int[]{};
Assert.assertTrue(ArrayUtils.isSameLength(null, emptyArr1));
Assert.assertTrue(ArrayUtils.isSameLength(new boolean[0], emptyArr1));
}
@Test
public void get() {
Object emptyArr1 = new int[]{0, 1, 2};
Assert.assertEquals(0, ArrayUtils.get(emptyArr1, 0));
Assert.assertEquals(1, ArrayUtils.get(emptyArr1, 1));
ArrayUtils.get(emptyArr1, 4);
}
@Test
public void getOrDefault() {
Object array = new int[]{0, 1, 2};
Assert.assertEquals(0, ArrayUtils.get(array, 0));
Assert.assertEquals(1, ArrayUtils.get(array, 1));
Assert.assertEquals(-1, ArrayUtils.get(array, 4, -1));
Assert.assertNull(ArrayUtils.get(array, 4));
}
@Test
public void set() {
int[] array = new int[]{0, -1, 2};
ArrayUtils.set(array, 1, 1);
Assert.assertArrayEquals(new int[]{0, 1, 2}, array);
}
@Test
public void equals() {
Assert.assertTrue(ArrayUtils.equals(null, (Object[]) null));
}
@Test
public void reverse() {
int[] array = new int[]{0, 1, 2, 3};
ArrayUtils.reverse(array);
Assert.assertArrayEquals(new int[]{3, 2, 1, 0}, array);
}
@Test
public void copy() {
int[] array = new int[]{0, 1, 2, 3};
int[] copy = ArrayUtils.copy(array);
Assert.assertArrayEquals(array, copy);
Assert.assertNotSame(array, copy);
}
@Test
public void subArray() {
int[] array = new int[]{0, 1, 2, 3};
int[] subArray = ArrayUtils.subArray(array, 1, 3);
Assert.assertArrayEquals(new int[]{1, 2}, subArray);
}
@Test
public void add() {
int[] array = new int[]{0, 1, 2, 3};
int[] addLastOne = ArrayUtils.add(array, 4);
int[] addFirstOne = ArrayUtils.add(array, 0, -1);
int[] addArr = ArrayUtils.add(array, new int[]{4, 5});
int[] addFirstArr = ArrayUtils.add(array, 0, new int[]{-2, -1});
int[] addMidArr = ArrayUtils.add(array, 2, new int[]{1, 2});
Assert.assertArrayEquals(new int[]{0, 1, 2, 3, 4}, addLastOne);
Assert.assertArrayEquals(new int[]{-1, 0, 1, 2, 3}, addFirstOne);
Assert.assertArrayEquals(new int[]{0, 1, 2, 3, 4, 5}, addArr);
Assert.assertArrayEquals(new int[]{-2, -1, 0, 1, 2, 3}, addFirstArr);
Assert.assertArrayEquals(new int[]{0, 1, 1, 2, 2, 3}, addMidArr);
}
@Test
public void remove() {
int[] array = new int[]{0, 1, 2, 3};
int[] remove = ArrayUtils.remove(array, 0);
Assert.assertArrayEquals(new int[]{1, 2, 3}, remove);
}
@Test
public void removeElement() {
int[] array = new int[]{0, 1, 2, 3};
int[] remove = ArrayUtils.removeElement(array, 0);
Assert.assertArrayEquals(new int[]{1, 2, 3}, remove);
}
@Test
public void indexOf() {
int[] array = new int[]{0, 1, 2, 3};
int i = ArrayUtils.indexOf(array, 0);
int i1 = ArrayUtils.indexOf(array, -1);
int i2 = ArrayUtils.indexOf(array, 0, 1);
Assert.assertEquals(0, i);
Assert.assertEquals(-1, i1);
Assert.assertEquals(-1, i2);
}
@Test
public void lastIndexOf() {
int[] array = new int[]{0, 1, 2, 3, 0};
int i = ArrayUtils.lastIndexOf(array, 0);
int i1 = ArrayUtils.lastIndexOf(array, -1);
int i2 = ArrayUtils.lastIndexOf(array, 0, 1);
Assert.assertEquals(4, i);
Assert.assertEquals(-1, i1);
Assert.assertEquals(0, i2);
}
@Test
public void contains() {
int[] array = new int[]{0, 1, 2, 3};
Assert.assertTrue(ArrayUtils.contains(array, 0));
Assert.assertFalse(ArrayUtils.contains(array, 4));
}
@Test
public void toPrimitive() {
int[] primitiveArray = new int[]{0, 1, 2, 3};
Integer[] array = new Integer[]{0, 1, 2, 3};
Assert.assertArrayEquals(primitiveArray, ArrayUtils.toPrimitive(array));
int[] primitiveArray1 = new int[]{0, 1, 2, 3, 0};
Integer[] array1 = new Integer[]{0, 1, 2, 3, null};
Assert.assertArrayEquals(primitiveArray1, ArrayUtils.toPrimitive(array1, 0));
}
@Test
public void toObject() {
int[] primitiveArray = new int[]{0, 1, 2, 3};
Integer[] array = new Integer[]{0, 1, 2, 3};
Assert.assertArrayEquals(array, ArrayUtils.toObject(primitiveArray));
}
@Test
public void asList() {
// Assert.assertEquals(0, ArrayUtils.asList(null).size());
List<Integer> list = ArrayUtils.asList(1, 2, 3, 4);
System.out.println(list);
}
@Test
public void sort() {
int[] ints = {2, 1, 0, 1, 2, 3};
ArrayUtils.sort(ints);
System.out.println(ArrayUtils.toString(ints));
}
@Test
public void forAllDo() {
ArrayUtils.forAllDo(null, null);
int[] array = new int[]{0, 1, 2, 3};
ArrayUtils.forAllDo(array, new ArrayUtils.Closure<Integer>() {
@Override
public void execute(int index, Integer item) {
System.out.println(index + ", " + item);
}
});
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/EncryptUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/EncryptUtilsTest.java | package com.blankj.utilcode.util;
import android.util.Pair;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import static com.blankj.utilcode.util.TestConfig.PATH_ENCRYPT;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/08/06
* desc : test EncryptUtils
* </pre>
*/
public class EncryptUtilsTest extends BaseTest {
@Test
public void encryptMD2() {
String blankjMD2 = "15435017570D8A73449E25C4622E17A4";
Assert.assertEquals(
blankjMD2,
EncryptUtils.encryptMD2ToString("blankj")
);
assertEquals(
blankjMD2,
EncryptUtils.encryptMD2ToString("blankj".getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjMD2),
EncryptUtils.encryptMD2("blankj".getBytes())
);
}
@Test
public void encryptMD5() {
String blankjMD5 = "AAC25CD336E01C8655F4EC7875445A60";
assertEquals(
blankjMD5,
EncryptUtils.encryptMD5ToString("blankj")
);
assertEquals(
blankjMD5,
EncryptUtils.encryptMD5ToString("blankj".getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjMD5),
EncryptUtils.encryptMD5("blankj".getBytes())
);
}
@Test
public void encryptMD5File() {
String fileMd5 = "7f138a09169b250e9dcb378140907378";
assertEquals(
fileMd5.toUpperCase(),
EncryptUtils.encryptMD5File2String(new File(PATH_ENCRYPT + "MD5.txt"))
);
}
@Test
public void encryptSHA1() {
String blankjSHA1 = "C606ACCB1FEB669E19D080ADDDDBB8E6CDA5F43C";
assertEquals(
blankjSHA1,
EncryptUtils.encryptSHA1ToString("blankj")
);
assertEquals(
blankjSHA1,
EncryptUtils.encryptSHA1ToString("blankj".getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjSHA1),
EncryptUtils.encryptSHA1("blankj".getBytes())
);
}
@Test
public void encryptSHA224() {
String blankjSHA224 = "F4C5C0E8CF56CAC4D06DB6B523F67621859A9D79BDA4B2AC03097D5F";
assertEquals(
blankjSHA224,
EncryptUtils.encryptSHA224ToString("blankj")
);
assertEquals(
blankjSHA224,
EncryptUtils.encryptSHA224ToString("blankj".getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjSHA224),
EncryptUtils.encryptSHA224("blankj".getBytes())
);
}
@Test
public void encryptSHA256() {
String blankjSHA256 = "8BD80AE90DFBA112786367BEBDDEE60A638EF5B82682EDF8F3D3CA8E6BFEF648";
assertEquals(
blankjSHA256,
EncryptUtils.encryptSHA256ToString("blankj")
);
assertEquals(
blankjSHA256,
EncryptUtils.encryptSHA256ToString("blankj".getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjSHA256),
EncryptUtils.encryptSHA256("blankj".getBytes()));
}
@Test
public void encryptSHA384() {
String blankjSHA384 = "BF831E5221FC108D6A72ACB888BA3EB0C030A5F01BA2F739856BE70681D86F992B85E0D461101C74BAEDA895BD422557";
assertEquals(
blankjSHA384,
EncryptUtils.encryptSHA384ToString("blankj")
);
assertEquals(
blankjSHA384,
EncryptUtils.encryptSHA384ToString("blankj".getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjSHA384),
EncryptUtils.encryptSHA384("blankj".getBytes())
);
}
@Test
public void encryptSHA512() {
String blankjSHA512 = "D59D31067F614ED3586F85A31FEFDB7F33096316DA26EBE0FF440B241C8560D96650F100D78C512560C976949EFA89CB5D5589DCF68C7FAADE98F03BCFEC2B45";
assertEquals(
blankjSHA512,
EncryptUtils.encryptSHA512ToString("blankj")
);
assertEquals(
blankjSHA512,
EncryptUtils.encryptSHA512ToString("blankj".getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjSHA512),
EncryptUtils.encryptSHA512("blankj".getBytes())
);
}
private String blankjHmacSHA512 =
"FC55AD54B95F55A8E32EA1BAD7748C157F80679F5561EC95A3EAD975316BA85363CB4AF6462D695F742F469EDC2D577272BE359A7F9E9C7018FDF4C921E1B3CF";
private String blankjHmackey = "blankj";
@Test
public void encryptHmacMD5() {
String blankjHmacMD5 = "2BA3FDABEE222522044BEC0CE5D6B490";
assertEquals(
blankjHmacMD5,
EncryptUtils.encryptHmacMD5ToString("blankj", blankjHmackey)
);
assertEquals(
blankjHmacMD5,
EncryptUtils.encryptHmacMD5ToString("blankj".getBytes(), blankjHmackey.getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjHmacMD5),
EncryptUtils.encryptHmacMD5("blankj".getBytes(), blankjHmackey.getBytes())
);
}
@Test
public void encryptHmacSHA1() {
String blankjHmacSHA1 = "88E83EFD915496860C83739BE2CF4752B2AC105F";
assertEquals(
blankjHmacSHA1,
EncryptUtils.encryptHmacSHA1ToString("blankj", blankjHmackey)
);
assertEquals(
blankjHmacSHA1,
EncryptUtils.encryptHmacSHA1ToString("blankj".getBytes(), blankjHmackey.getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjHmacSHA1),
EncryptUtils.encryptHmacSHA1("blankj".getBytes(), blankjHmackey.getBytes())
);
}
@Test
public void encryptHmacSHA224() {
String blankjHmacSHA224 = "E392D83D1030323FB2E062E8165A3AD38366E53DF19EA3290961E153";
assertEquals(
blankjHmacSHA224,
EncryptUtils.encryptHmacSHA224ToString("blankj", blankjHmackey)
);
assertEquals(
blankjHmacSHA224,
EncryptUtils.encryptHmacSHA224ToString("blankj".getBytes(), blankjHmackey.getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjHmacSHA224),
EncryptUtils.encryptHmacSHA224("blankj".getBytes(), blankjHmackey.getBytes())
);
}
@Test
public void encryptHmacSHA256() {
String blankjHmacSHA256 = "A59675F13FC9A6E06D8DC90D4DC01DB9C991B0B95749D2471E588BF311DA2C67";
assertEquals(
blankjHmacSHA256,
EncryptUtils.encryptHmacSHA256ToString("blankj", blankjHmackey)
);
assertEquals(
blankjHmacSHA256,
EncryptUtils.encryptHmacSHA256ToString("blankj".getBytes(), blankjHmackey.getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjHmacSHA256),
EncryptUtils.encryptHmacSHA256("blankj".getBytes(), blankjHmackey.getBytes())
);
}
@Test
public void encryptHmacSHA384() {
String blankjHmacSHA384 = "9FC2F49C7EDE698EA59645B3BEFBBE67DCC7D6623E03D4D03CDA1324F7B6445BC428AB42F6A962CF79AFAD1302C3223D";
assertEquals(
blankjHmacSHA384,
EncryptUtils.encryptHmacSHA384ToString("blankj", blankjHmackey)
);
assertEquals(
blankjHmacSHA384,
EncryptUtils.encryptHmacSHA384ToString("blankj".getBytes(), blankjHmackey.getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjHmacSHA384),
EncryptUtils.encryptHmacSHA384("blankj".getBytes(), blankjHmackey.getBytes())
);
}
@Test
public void encryptHmacSHA512() {
assertEquals(
blankjHmacSHA512,
EncryptUtils.encryptHmacSHA512ToString("blankj", blankjHmackey)
);
assertEquals(
blankjHmacSHA512,
EncryptUtils.encryptHmacSHA512ToString("blankj".getBytes(), blankjHmackey.getBytes())
);
assertArrayEquals(
UtilsBridge.hexString2Bytes(blankjHmacSHA512),
EncryptUtils.encryptHmacSHA512("blankj".getBytes(), blankjHmackey.getBytes())
);
}
private String dataDES = "0008DB3345AB0223";
private String keyDES = "6801020304050607";
private String resDES = "1F7962581118F360";
private byte[] bytesDataDES = UtilsBridge.hexString2Bytes(dataDES);
private byte[] bytesKeyDES = UtilsBridge.hexString2Bytes(keyDES);
private byte[] bytesResDES = UtilsBridge.hexString2Bytes(resDES);
@Test
public void encryptDES() {
assertArrayEquals(
bytesResDES,
EncryptUtils.encryptDES(bytesDataDES, bytesKeyDES, "DES/ECB/NoPadding", null)
);
assertEquals(
resDES,
EncryptUtils.encryptDES2HexString(bytesDataDES, bytesKeyDES, "DES/ECB/NoPadding", null)
);
assertArrayEquals(
UtilsBridge.base64Encode(bytesResDES),
EncryptUtils.encryptDES2Base64(bytesDataDES, bytesKeyDES, "DES/ECB/NoPadding", null)
);
}
@Test
public void decryptDES() {
assertArrayEquals(
bytesDataDES,
EncryptUtils.decryptDES(bytesResDES, bytesKeyDES, "DES/ECB/NoPadding", null)
);
assertArrayEquals(
bytesDataDES,
EncryptUtils.decryptHexStringDES(resDES, bytesKeyDES, "DES/ECB/NoPadding", null)
);
assertArrayEquals(
bytesDataDES,
EncryptUtils.decryptBase64DES(UtilsBridge.base64Encode(bytesResDES), bytesKeyDES, "DES/ECB/NoPadding", null)
);
}
private String data3DES = "1111111111111111";
private String key3DES = "111111111111111111111111111111111111111111111111";
private String res3DES = "F40379AB9E0EC533";
private byte[] bytesDataDES3 = UtilsBridge.hexString2Bytes(data3DES);
private byte[] bytesKeyDES3 = UtilsBridge.hexString2Bytes(key3DES);
private byte[] bytesResDES3 = UtilsBridge.hexString2Bytes(res3DES);
@Test
public void encrypt3DES() {
assertArrayEquals(
bytesResDES3,
EncryptUtils.encrypt3DES(bytesDataDES3, bytesKeyDES3, "DESede/ECB/NoPadding", null)
);
assertEquals(
res3DES,
EncryptUtils.encrypt3DES2HexString(bytesDataDES3, bytesKeyDES3, "DESede/ECB/NoPadding", null)
);
assertArrayEquals(
UtilsBridge.base64Encode(bytesResDES3),
EncryptUtils.encrypt3DES2Base64(bytesDataDES3, bytesKeyDES3, "DESede/ECB/NoPadding", null)
);
}
@Test
public void decrypt3DES() {
assertArrayEquals(
bytesDataDES3,
EncryptUtils.decrypt3DES(bytesResDES3, bytesKeyDES3, "DESede/ECB/NoPadding", null)
);
assertArrayEquals(
bytesDataDES3,
EncryptUtils.decryptHexString3DES(res3DES, bytesKeyDES3, "DESede/ECB/NoPadding", null)
);
assertArrayEquals(
bytesDataDES3,
EncryptUtils.decryptBase64_3DES(UtilsBridge.base64Encode(bytesResDES3), bytesKeyDES3, "DESede/ECB/NoPadding", null)
);
}
private String dataAES = "111111111111111111111111111111111";
private String keyAES = "11111111111111111111111111111111";
private String resAES = "393FBBBC2C774BE50A106A50393E623AC3790781D015BB854359587256581F6D";
private byte[] bytesDataAES = UtilsBridge.hexString2Bytes(dataAES);
private byte[] bytesKeyAES = UtilsBridge.hexString2Bytes(keyAES);
private byte[] bytesResAES = UtilsBridge.hexString2Bytes(resAES);
@Test
public void encryptAES() {
assertArrayEquals(
bytesResAES,
EncryptUtils.encryptAES(bytesDataAES, bytesKeyAES, "AES/ECB/PKCS5Padding", null)
);
assertEquals(
resAES,
EncryptUtils.encryptAES2HexString(bytesDataAES, bytesKeyAES, "AES/ECB/PKCS5Padding", null)
);
assertArrayEquals(
UtilsBridge.base64Encode(bytesResAES),
EncryptUtils.encryptAES2Base64(bytesDataAES, bytesKeyAES, "AES/ECB/PKCS5Padding", null)
);
}
@Test
public void decryptAES() {
assertArrayEquals(
bytesDataAES,
EncryptUtils.decryptAES(bytesResAES, bytesKeyAES, "AES/ECB/PKCS5Padding", null)
);
assertArrayEquals(
bytesDataAES,
EncryptUtils.decryptHexStringAES(resAES, bytesKeyAES, "AES/ECB/PKCS5Padding", null)
);
assertArrayEquals(bytesDataAES,
EncryptUtils.decryptBase64AES(UtilsBridge.base64Encode(bytesResAES), bytesKeyAES, "AES/ECB/PKCS5Padding", null)
);
}
@Test
public void encryptDecryptRSA() throws Exception {
int keySize = 1024;
Pair<String, String> publicPrivateKey = genKeyPair(keySize);
String publicKey = publicPrivateKey.first;
String privateKey = publicPrivateKey.second;
String dataRSA = "BlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBlankjBl";
System.out.println("publicKeyBase64:" + publicKey);
System.out.println("privateKeyBase64:" + privateKey);
System.out.println(EncryptUtils.encryptRSA2HexString(
dataRSA.getBytes(),
UtilsBridge.base64Decode(publicKey.getBytes()),
keySize,
"RSA/None/PKCS1Padding"
));
assertArrayEquals(EncryptUtils.decryptRSA(
EncryptUtils.encryptRSA(
dataRSA.getBytes(),
UtilsBridge.base64Decode(publicKey.getBytes()),
keySize,
"RSA/None/PKCS1Padding"
),
UtilsBridge.base64Decode(privateKey.getBytes()),
keySize,
"RSA/None/PKCS1Padding"
), dataRSA.getBytes());
}
private String dataRc4 = "111111111111111111111";
private String keyRc4 = "111111111111";
@Test
public void rc4() throws Exception {
System.out.println(new String(EncryptUtils.rc4(EncryptUtils.rc4(dataRc4.getBytes(), keyRc4.getBytes()), keyRc4.getBytes())));
}
private Pair<String, String> genKeyPair(int size) throws NoSuchAlgorithmException {
if (size == 1024) {
return Pair.create(
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYHGvdORdwsK5i+s9rKaMPL1O5eDK2XwNHRUWaxmGB/cxLxeinJrrqdAN+mME7XtGN9bklnOR3MUBQLVnWIn/IU0pnIJY9DpPTVc7x+1zFb8UUq1N0BBo/NpUG5olxuQULuAAHZOg28pnP/Pcb5XVEvpNKL0HaWjN8pu/Dzf8gZwIDAQAB",
"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJgca905F3CwrmL6z2spow8vU7l4MrZfA0dFRZrGYYH9zEvF6Kcmuup0A36YwTte0Y31uSWc5HcxQFAtWdYif8hTSmcglj0Ok9NVzvH7XMVvxRSrU3QEGj82lQbmiXG5BQu4AAdk6Dbymc/89xvldUS+k0ovQdpaM3ym78PN/yBnAgMBAAECgYAFdX+pgNMGiFC53KZ1AhmIAfrPPTEUunQzqpjE5Tm6oJEkZwXiedFbeK5nbLQCnXSH07nBT9AjNvFH71i6BqLvT1l3/ezPq9pmRPriHfWQQ3/J3ASf1O9F9CkYbq/s/qqkXEFcl8PdYQV0xU/kS4jZPP+60Lv3sPkLg2DpkhM+AQJBANTl+/v6sBqqQSS0Anl5nE15Ck3XGBcq0nvATHfFkJYtG9rrXz3ZoRATLxF1iJYwGSAtirhev9W7qFayjci0ztcCQQC25/kkFbeMEWT6/kyV8wcPIog1mKy8RVB9+2l6C8AzbWBPZYtLlB7uaGSJeZBTEGfvRYzpFm5xO0JqwCfDddjxAkBmxtgM3wqg9MwaAeSn6/Nu2x4EUfBJTtzp7P19XJzeQsyNtM73ttYwQnKYhRr5FiMrC5FKTENj1QIBSJV17QNlAkAL5cUAAuWgl9UQuo/yxQ81fdKMYfUCfiPBPiRbSv5imf/Eyl8oOGdWrLW1d5HaxVttZgHHe60NcoRce0la3oSRAkAe8OqLsm9ryXNvBtZxSG+1JUvePVxpRSlJdZIAUKxN6XQE0S9aEe/IkNDBgVeiUEtop76R2NkkGtGTwzbzl0gm"
);
} else if (size == 2048) {
return Pair.create(
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjLLeJZIO7dfQKb6tHE+TlhvD1m3UdTefKvl4uNQboDXy2ztgPcksjLDXxsT+znxMBh4RpXxfVPgnrcSLewGVhTb3uXh9sWo6tvvshNaMKBTebaZePhE7grq+LHH3NILscVssK24rDSvIquZ4nUbDipF/Iscge4LwnypcCuun/3RCn4HYzXW+0YFFZC8Vq4zabIxtzzkvgZlAlvuD6tT76Uuo5kD8b36yYNALI+ZStOj283wlL8PgyyitRGaqCH+MjWYqDb5C0DN31kcoSU7ARTGWgNNAoexAdNujkBvVRFyR2cH9FpjJDu18Oa8v9uSjlRftVWPj0OQXE7vRUsrrawIDAQAB",
"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCMst4lkg7t19Apvq0cT5OWG8PWbdR1N58q+Xi41BugNfLbO2A9ySyMsNfGxP7OfEwGHhGlfF9U+CetxIt7AZWFNve5eH2xajq2++yE1owoFN5tpl4+ETuCur4scfc0guxxWywrbisNK8iq5nidRsOKkX8ixyB7gvCfKlwK66f/dEKfgdjNdb7RgUVkLxWrjNpsjG3POS+BmUCW+4Pq1PvpS6jmQPxvfrJg0Asj5lK06PbzfCUvw+DLKK1EZqoIf4yNZioNvkLQM3fWRyhJTsBFMZaA00Ch7EB026OQG9VEXJHZwf0WmMkO7Xw5ry/25KOVF+1VY+PQ5BcTu9FSyutrAgMBAAECggEAHJQ4i2kfnzA3GEOi5h1D3TnGjcfBYA3sRs5ltyVedyx+KAnngqVaZzmEmtto5ohY6OUysGqS8q91X9aMfm/T7zs7FnFjFqZ9Rq3lXRY3YezbQWqJuhHGBMfp2R1NGV1+qYfbcPbvx70dBZnK5id5kKv9JxNLhcsTFUGFcLJtbXXixY2CGiS/dIbFvFHGMbAz3+9l9HXaL4AS7KQXvnauwJW1a5vIAVFYZVBj0qY9Viy2vq6ShH+9pdxOSsWBt08WpxIhjkTr+ZkFck67la2Jn0SBlClB0FIygTqbAmsM3p1nqcR55jdx3hfs31rIfM1Rx5epMm48KYErb2ktowngAQKBgQDL9FEumMMagPy4+EjR1puFHNvADlAi8tIUNt1W5zKKnd+T6gYGn8nqiiy5pvwLLUp8JISmq50tMC3cgAPw+G4kIe5zoBO2EU9X6aPhMd/ScUlVdk0IzEMXa3kMAOjOInWvoevJ4cwWcBPH2aRuDg5wZdh3TpB9LQP4uQ0QHwmE3wKBgQCwmkL6rJDrNo1GNUsjw+WIsXkuS3PYJahbg/uhRdGSsX2BRIPQVCRJP7MkgaUMhZRilt1ROfQy4d2BPxTxvUiGJcKfpsW8xi39PrYWZC5TvEA839q39Uak+ISCsYtZaHk5dvzmE9nF5gv0ivjCr81N2/1KwXO8VmNofzWUqNd+9QKBgQCs39QICRgm2Ppd1qXyp1N/SuzBJ+CpHuUOmUqXpLRkZljiSVT+PGar1J8AZhfxaVxfSZzeoUxCxzm4UxIEKK9DFTfG7gKHKrj0LWfpM5siB0A/nlzBflHIAiLCF+s8/lx+mGMB5dBVnH5HwaTsXCHFB66pwgAa+hMJueDmr0gkRQKBgDKhd1Rwxvd4Y1ZejxVI43SmFOzt2t98JGFgXHLnFmdtFWNLJlNC3EhXx99Of+gwH9OIFxljeRxhXuTgFfwcXT+AceTdplExrBuvr/qJbDK7hNsu/oDBBCjlyu/BQQc4CZEtCOJZjJTNGF5avWjrh/urd1nITosPZV6fIdhl86pFAoGAfOwK0Wte6gO5glAHP9RNktDeyFJCfFH1KUFiAG7XUww6bRpL2fEAqBIcDVgsS565ihxDSbUjgQgg/Ckh2+iBrwf1K9ViO4XUuwWqRS26rn4Is/W5kbPtnC4HS5cQIH1aWi3xUMJcWxV4ZrwiMVdw91leYWC0IbXC/yrc/PBW+sE="
);
}
SecureRandom secureRandom = new SecureRandom();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(size, secureRandom);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Key publicKey = keyPair.getPublic();
Key privateKey = keyPair.getPrivate();
byte[] publicKeyBytes = publicKey.getEncoded();
byte[] privateKeyBytes = privateKey.getEncoded();
String publicKeyBase64 = EncodeUtils.base64Encode2String(publicKeyBytes);
String privateKeyBase64 = EncodeUtils.base64Encode2String(privateKeyBytes);
return Pair.create(publicKeyBase64, privateKeyBase64);
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/StringUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/StringUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/08/16
* desc : test StringUtils
* </pre>
*/
public class StringUtilsTest extends BaseTest {
@Test
public void isEmpty() {
assertTrue(StringUtils.isEmpty(""));
assertTrue(StringUtils.isEmpty(null));
assertFalse(StringUtils.isEmpty(" "));
}
@Test
public void isTrimEmpty() {
assertTrue(StringUtils.isTrimEmpty(""));
assertTrue(StringUtils.isTrimEmpty(null));
assertTrue(StringUtils.isTrimEmpty(" "));
}
@Test
public void isSpace() {
assertTrue(StringUtils.isSpace(""));
assertTrue(StringUtils.isSpace(null));
assertTrue(StringUtils.isSpace(" "));
assertTrue(StringUtils.isSpace(" \n\t\r"));
}
@Test
public void equals() {
assertTrue(StringUtils.equals(null, null));
assertTrue(StringUtils.equals("blankj", "blankj"));
assertFalse(StringUtils.equals("blankj", "Blankj"));
}
@Test
public void equalsIgnoreCase() {
assertTrue(StringUtils.equalsIgnoreCase(null, null));
assertFalse(StringUtils.equalsIgnoreCase(null, "blankj"));
assertTrue(StringUtils.equalsIgnoreCase("blankj", "Blankj"));
assertTrue(StringUtils.equalsIgnoreCase("blankj", "blankj"));
assertFalse(StringUtils.equalsIgnoreCase("blankj", "blank"));
}
@Test
public void null2Length0() {
assertEquals("", StringUtils.null2Length0(null));
}
@Test
public void length() {
assertEquals(0, StringUtils.length(null));
assertEquals(0, StringUtils.length(""));
assertEquals(6, StringUtils.length("blankj"));
}
@Test
public void upperFirstLetter() {
assertEquals("Blankj", StringUtils.upperFirstLetter("blankj"));
assertEquals("Blankj", StringUtils.upperFirstLetter("Blankj"));
assertEquals("1Blankj", StringUtils.upperFirstLetter("1Blankj"));
}
@Test
public void lowerFirstLetter() {
assertEquals("blankj", StringUtils.lowerFirstLetter("blankj"));
assertEquals("blankj", StringUtils.lowerFirstLetter("Blankj"));
assertEquals("1blankj", StringUtils.lowerFirstLetter("1blankj"));
}
@Test
public void reverse() {
assertEquals("jknalb", StringUtils.reverse("blankj"));
assertEquals("knalb", StringUtils.reverse("blank"));
assertEquals("文中试测", StringUtils.reverse("测试中文"));
assertEquals("", StringUtils.reverse(null));
}
@Test
public void toDBC() {
assertEquals(" ,.&", StringUtils.toDBC(" ,.&"));
}
@Test
public void toSBC() {
assertEquals(" ,.&", StringUtils.toSBC(" ,.&"));
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/NumberUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/NumberUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Assert;
import org.junit.Test;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2020/04/13
* desc : test NumberUtils
* </pre>
*/
public class NumberUtilsTest {
@Test
public void format() {
double val = Math.PI * 100000;// 314159.2653589793
Assert.assertEquals("314159.27", NumberUtils.format(val, 2));
Assert.assertEquals("314159.265", NumberUtils.format(val, 3));
Assert.assertEquals("314159.27", NumberUtils.format(val, 2, true));
Assert.assertEquals("314159.26", NumberUtils.format(val, 2, false));
Assert.assertEquals("00314159.27", NumberUtils.format(val, 8, 2, true));
Assert.assertEquals("0000314159.27", NumberUtils.format(val, 10, 2, true));
Assert.assertEquals("314,159.27", NumberUtils.format(val, true, 2));
Assert.assertEquals("314159.27", NumberUtils.format(val, false, 2));
Assert.assertEquals("314159.27", NumberUtils.format(val, false, 2, true));
Assert.assertEquals("314159.26", NumberUtils.format(val, false, 2, false));
Assert.assertEquals("314159.27", NumberUtils.format(val, false, 2, true));
Assert.assertEquals("314159.265", NumberUtils.format(val, false, 3, false));
}
@Test
public void float2Double() {
float val = 3.14f;
System.out.println((double) val);
System.out.println(NumberUtils.float2Double(val));
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/ImageUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/ImageUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Assert;
import org.junit.Test;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/08/25
* desc : test ImageUtils
* </pre>
*/
public class ImageUtilsTest extends BaseTest {
@Test
public void getImageType() {
Assert.assertEquals(ImageUtils.ImageType.TYPE_JPG, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.jpg"));
Assert.assertEquals(ImageUtils.ImageType.TYPE_PNG, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.png"));
Assert.assertEquals(ImageUtils.ImageType.TYPE_GIF, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.gif"));
Assert.assertEquals(ImageUtils.ImageType.TYPE_TIFF, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.tif"));
Assert.assertEquals(ImageUtils.ImageType.TYPE_BMP, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.bmp"));
Assert.assertEquals(ImageUtils.ImageType.TYPE_WEBP, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.webp"));
Assert.assertEquals(ImageUtils.ImageType.TYPE_ICO, ImageUtils.getImageType(TestConfig.PATH_IMAGE + "ic_launcher.ico"));
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/ConvertUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/ConvertUtilsTest.java | package com.blankj.utilcode.util;
import com.blankj.utilcode.constant.MemoryConstants;
import com.blankj.utilcode.constant.TimeConstants;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/08/13
* desc : test ConvertUtils
* </pre>
*/
public class ConvertUtilsTest extends BaseTest {
private byte[] mBytes = new byte[]{0x00, 0x08, (byte) 0xdb, 0x33, 0x45, (byte) 0xab, 0x02, 0x23};
private String hexString = "0008DB3345AB0223";
private char[] mChars1 = new char[]{'0', '1', '2'};
private byte[] mBytes1 = new byte[]{48, 49, 50};
@Test
public void bytes2HexString() {
assertEquals(
hexString,
ConvertUtils.bytes2HexString(mBytes)
);
}
@Test
public void hexString2Bytes() {
assertTrue(
Arrays.equals(
mBytes,
ConvertUtils.hexString2Bytes(hexString)
)
);
}
@Test
public void chars2Bytes() {
assertTrue(
Arrays.equals(
mBytes1,
ConvertUtils.chars2Bytes(mChars1)
)
);
}
@Test
public void bytes2Chars() {
assertTrue(
Arrays.equals(
mChars1,
ConvertUtils.bytes2Chars(mBytes1)
)
);
}
@Test
public void byte2MemorySize() {
assertEquals(
1024,
ConvertUtils.byte2MemorySize(MemoryConstants.GB, MemoryConstants.MB),
0.001
);
}
@Test
public void byte2FitMemorySize() {
assertEquals(
"3.098MB",
ConvertUtils.byte2FitMemorySize(1024 * 1024 * 3 + 1024 * 100)
);
}
@Test
public void millis2FitTimeSpan() {
long millis = 6 * TimeConstants.DAY
+ 6 * TimeConstants.HOUR
+ 6 * TimeConstants.MIN
+ 6 * TimeConstants.SEC
+ 6;
assertEquals(
"6天6小时6分钟6秒6毫秒",
ConvertUtils.millis2FitTimeSpan(millis, 7)
);
assertEquals(
"6天6小时6分钟6秒",
ConvertUtils.millis2FitTimeSpan(millis, 4)
);
assertEquals(
"6天6小时6分钟",
ConvertUtils.millis2FitTimeSpan(millis, 3)
);
assertEquals(
"25天24分钟24秒24毫秒",
ConvertUtils.millis2FitTimeSpan(millis * 4, 5)
);
}
@Test
public void bytes2Bits_bits2Bytes() {
assertEquals(
"0111111111111010",
ConvertUtils.bytes2Bits(new byte[]{0x7F, (byte) 0xFA})
);
assertEquals(
"0111111111111010",
ConvertUtils.bytes2Bits(ConvertUtils.bits2Bytes("111111111111010"))
);
}
@Test
public void inputStream2Bytes_bytes2InputStream() throws Exception {
String string = "this is test string";
assertTrue(
Arrays.equals(
string.getBytes("UTF-8"),
ConvertUtils.inputStream2Bytes(ConvertUtils.bytes2InputStream(string.getBytes("UTF-8")))
)
);
}
@Test
public void inputStream2String_string2InputStream() {
String string = "this is test string";
assertEquals(
string,
ConvertUtils.inputStream2String(ConvertUtils.string2InputStream(string, "UTF-8"), "UTF-8")
);
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/ColorUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/ColorUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/01/15
* desc : test ColorUtils
* </pre>
*/
public class ColorUtilsTest extends BaseTest {
@Test
public void setAlphaComponent() {
assertEquals(0x80ffffff, ColorUtils.setAlphaComponent(0xffffffff, 0x80));
assertEquals(0x80ffffff, ColorUtils.setAlphaComponent(0xffffffff, 0.5f));
}
@Test
public void setRedComponent() {
assertEquals(0xff80ffff, ColorUtils.setRedComponent(0xffffffff, 0x80));
assertEquals(0xff80ffff, ColorUtils.setRedComponent(0xffffffff, 0.5f));
}
@Test
public void setGreenComponent() {
assertEquals(0xffff80ff, ColorUtils.setGreenComponent(0xffffffff, 0x80));
assertEquals(0xffff80ff, ColorUtils.setGreenComponent(0xffffffff, 0.5f));
}
@Test
public void setBlueComponent() {
assertEquals(0xffffff80, ColorUtils.setBlueComponent(0xffffffff, 0x80));
assertEquals(0xffffff80, ColorUtils.setBlueComponent(0xffffffff, 0.5f));
}
@Test
public void string2Int() {
assertEquals(0xffffffff, ColorUtils.string2Int("#ffffff"));
assertEquals(0xffffffff, ColorUtils.string2Int("#ffffffff"));
assertEquals(0xffffffff, ColorUtils.string2Int("white"));
}
@Test
public void int2RgbString() {
assertEquals("#000001", ColorUtils.int2RgbString(1));
assertEquals("#ffffff", ColorUtils.int2RgbString(0xffffff));
}
@Test
public void int2ArgbString() {
assertEquals("#ff000001", ColorUtils.int2ArgbString(1));
assertEquals("#ffffffff", ColorUtils.int2ArgbString(0xffffff));
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheMemoryUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheMemoryUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/06/13
* desc : test CacheMemoryUtils
* </pre>
*/
public class CacheMemoryUtilsTest extends BaseTest {
private CacheMemoryUtils mCacheMemoryUtils1 = CacheMemoryUtils.getInstance();
private CacheMemoryUtils mCacheMemoryUtils2 = CacheMemoryUtils.getInstance(3);
@Before
public void setUp() {
for (int i = 0; i < 10; i++) {
mCacheMemoryUtils1.put(String.valueOf(i), i);
}
for (int i = 0; i < 10; i++) {
mCacheMemoryUtils2.put(String.valueOf(i), i);
}
}
@Test
public void get() {
for (int i = 0; i < 10; i++) {
assertEquals(i, mCacheMemoryUtils1.get(String.valueOf(i)));
}
for (int i = 0; i < 10; i++) {
if (i < 7) {
assertNull(mCacheMemoryUtils2.get(String.valueOf(i)));
} else {
assertEquals(i, mCacheMemoryUtils2.get(String.valueOf(i)));
}
}
}
@Test
public void getExpired() throws Exception {
mCacheMemoryUtils1.put("10", 10, 2 * CacheMemoryUtils.SEC);
assertEquals(10, mCacheMemoryUtils1.get("10"));
Thread.sleep(1500);
assertEquals(10, mCacheMemoryUtils1.get("10"));
Thread.sleep(1500);
assertNull(mCacheMemoryUtils1.get("10"));
}
@Test
public void getDefault() {
assertNull(mCacheMemoryUtils1.get("10"));
assertEquals("10", mCacheMemoryUtils1.get("10", "10"));
}
@Test
public void getCacheCount() {
assertEquals(10, mCacheMemoryUtils1.getCacheCount());
assertEquals(3, mCacheMemoryUtils2.getCacheCount());
}
@Test
public void remove() {
assertEquals(0, mCacheMemoryUtils1.remove("0"));
assertNull(mCacheMemoryUtils1.get("0"));
assertNull(mCacheMemoryUtils1.remove("0"));
}
@Test
public void clear() {
mCacheMemoryUtils1.clear();
mCacheMemoryUtils2.clear();
for (int i = 0; i < 10; i++) {
assertNull(mCacheMemoryUtils1.get(String.valueOf(i)));
}
for (int i = 0; i < 10; i++) {
assertNull(mCacheMemoryUtils2.get(String.valueOf(i)));
}
assertEquals(0, mCacheMemoryUtils1.getCacheCount());
assertEquals(0, mCacheMemoryUtils2.getCacheCount());
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/PathUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/PathUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2020/04/09
* desc :
* </pre>
*/
public class PathUtilsTest extends BaseTest {
@Test
public void join() {
assertEquals(PathUtils.join("", ""), "");
assertEquals(PathUtils.join("", "data"), "/data");
assertEquals(PathUtils.join("", "//data"), "/data");
assertEquals(PathUtils.join("", "data//"), "/data");
assertEquals(PathUtils.join("", "//data//"), "/data");
assertEquals(PathUtils.join("/sdcard", "data"), "/sdcard/data");
assertEquals(PathUtils.join("/sdcard/", "data"), "/sdcard/data");
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/UiMessageUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/UiMessageUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Test;
import androidx.annotation.NonNull;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/10/21
* desc : test UiMessageUtils
* </pre>
*/
public class UiMessageUtilsTest extends BaseTest {
@Test
public void singleMessageTest() {
UiMessageUtils.UiMessageCallback listener = new UiMessageUtils.UiMessageCallback() {
@Override
public void handleMessage(@NonNull UiMessageUtils.UiMessage localMessage) {
System.out.println("receive -> " + localMessage.getId() + ": " + localMessage.getObject());
}
};
UiMessageUtils.getInstance().addListener(listener);
UiMessageUtils.getInstance().send(1, "msg");
UiMessageUtils.getInstance().removeListener(listener);
UiMessageUtils.getInstance().send(1, "msg");
}
@Test
public void multiMessageTest() {
UiMessageUtils.UiMessageCallback listener = new UiMessageUtils.UiMessageCallback() {
@Override
public void handleMessage(@NonNull UiMessageUtils.UiMessage localMessage) {
switch (localMessage.getId()) {
case 1:
System.out.println("receive -> 1: " + localMessage.getObject());
break;
case 2:
System.out.println("receive -> 2: " + localMessage.getObject());
break;
case 4:
System.out.println("receive -> 4: " + localMessage.getObject());
break;
}
}
};
UiMessageUtils.getInstance().addListener(listener);
UiMessageUtils.getInstance().send(1, "msg1");
UiMessageUtils.getInstance().send(2, "msg2");
UiMessageUtils.getInstance().send(4, "msg4");
UiMessageUtils.getInstance().removeListener(listener);
UiMessageUtils.getInstance().send(1, "msg1");
UiMessageUtils.getInstance().send(2, "msg2");
UiMessageUtils.getInstance().send(4, "msg4");
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/BaseTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/BaseTest.java | package com.blankj.utilcode.util;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLog;
import java.util.concurrent.Executor;
import androidx.annotation.NonNull;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/08/03
* desc :
* </pre>
*/
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, shadows = {ShadowLog.class})
public class BaseTest {
@BusUtils.Bus(tag = "base")
public void noParamFun(int i) {
System.out.println("base" + i);
}
public BaseTest() {
ShadowLog.stream = System.out;
ThreadUtils.setDeliver(new Executor() {
@Override
public void execute(@NonNull Runnable command) {
command.run();
}
});
Utils.init(RuntimeEnvironment.application);
}
@Test
public void test() throws Exception {
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/EncodeUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/EncodeUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/08/12
* desc : test EncodeUtils
* </pre>
*/
public class EncodeUtilsTest extends BaseTest {
@Test
public void urlEncode_urlDecode() {
String urlEncodeString = "%E5%93%88%E5%93%88%E5%93%88";
assertEquals(urlEncodeString, EncodeUtils.urlEncode("哈哈哈"));
assertEquals(urlEncodeString, EncodeUtils.urlEncode("哈哈哈", "UTF-8"));
assertEquals("哈哈哈", EncodeUtils.urlDecode(urlEncodeString));
assertEquals("哈哈哈", EncodeUtils.urlDecode(urlEncodeString, "UTF-8"));
}
@Test
public void base64Decode_base64Encode() {
assertArrayEquals("blankj".getBytes(), EncodeUtils.base64Decode(EncodeUtils.base64Encode("blankj")));
assertArrayEquals("blankj".getBytes(), EncodeUtils.base64Decode(EncodeUtils.base64Encode2String("blankj".getBytes())));
assertEquals(
"Ymxhbmtq",
EncodeUtils.base64Encode2String("blankj".getBytes())
);
assertArrayEquals("Ymxhbmtq".getBytes(), EncodeUtils.base64Encode("blankj".getBytes()));
}
@Test
public void htmlEncode_htmlDecode() {
String html = "<html>" +
"<head>" +
"<title>我的第一个 HTML 页面</title>" +
"</head>" +
"<body>" +
"<p>body 元素的内容会显示在浏览器中。</p>" +
"<p>title 元素的内容会显示在浏览器的标题栏中。</p>" +
"</body>" +
"</html>";
String encodeHtml = "<html><head><title>我的第一个 HTML 页面</title></head><body><p>body 元素的内容会显示在浏览器中。</p><p>title 元素的内容会显示在浏览器的标题栏中。</p></body></html>";
assertEquals(encodeHtml, EncodeUtils.htmlEncode(html));
assertEquals(html, EncodeUtils.htmlDecode(encodeHtml).toString());
}
@Test
public void binEncode_binDecode() {
String test = "test";
String binary = EncodeUtils.binaryEncode(test);
assertEquals("test", EncodeUtils.binaryDecode(binary));
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/ObjectUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/ObjectUtilsTest.java | package com.blankj.utilcode.util;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.util.SparseLongArray;
import org.junit.Test;
import java.util.HashMap;
import java.util.LinkedList;
import androidx.collection.LongSparseArray;
import androidx.collection.SimpleArrayMap;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/12/24
* desc : test ObjectUtils
* </pre>
*/
public class ObjectUtilsTest extends BaseTest {
@Test
public void isEmpty() {
StringBuilder sb = new StringBuilder("");
StringBuilder sb1 = new StringBuilder(" ");
String string = "";
String string1 = " ";
int[][] arr = new int[][]{};
LinkedList<Integer> list = new LinkedList<>();
HashMap<String, Integer> map = new HashMap<>();
SimpleArrayMap<String, Integer> sam = new SimpleArrayMap<>();
SparseArray<String> sa = new SparseArray<>();
SparseBooleanArray sba = new SparseBooleanArray();
SparseIntArray sia = new SparseIntArray();
SparseLongArray sla = new SparseLongArray();
LongSparseArray<String> lsa = new LongSparseArray<>();
android.util.LongSparseArray<String> lsaV4 = new android.util.LongSparseArray<>();
assertTrue(ObjectUtils.isEmpty(sb));
assertFalse(ObjectUtils.isEmpty(sb1));
assertTrue(ObjectUtils.isEmpty(string));
assertFalse(ObjectUtils.isEmpty(string1));
assertTrue(ObjectUtils.isEmpty(arr));
assertTrue(ObjectUtils.isEmpty(list));
assertTrue(ObjectUtils.isEmpty(map));
assertTrue(ObjectUtils.isEmpty(sam));
assertTrue(ObjectUtils.isEmpty(sa));
assertTrue(ObjectUtils.isEmpty(sba));
assertTrue(ObjectUtils.isEmpty(sia));
assertTrue(ObjectUtils.isEmpty(sla));
assertTrue(ObjectUtils.isEmpty(lsa));
assertTrue(ObjectUtils.isEmpty(lsaV4));
assertTrue(!ObjectUtils.isNotEmpty(sb));
assertFalse(!ObjectUtils.isNotEmpty(sb1));
assertTrue(!ObjectUtils.isNotEmpty(string));
assertFalse(!ObjectUtils.isNotEmpty(string1));
assertTrue(!ObjectUtils.isNotEmpty(arr));
assertTrue(!ObjectUtils.isNotEmpty(list));
assertTrue(!ObjectUtils.isNotEmpty(map));
assertTrue(!ObjectUtils.isNotEmpty(sam));
assertTrue(!ObjectUtils.isNotEmpty(sa));
assertTrue(!ObjectUtils.isNotEmpty(sba));
assertTrue(!ObjectUtils.isNotEmpty(sia));
assertTrue(!ObjectUtils.isNotEmpty(sla));
assertTrue(!ObjectUtils.isNotEmpty(lsa));
assertTrue(!ObjectUtils.isNotEmpty(lsaV4));
}
@Test
public void equals() {
assertTrue(ObjectUtils.equals(1, 1));
assertTrue(ObjectUtils.equals("str", "str"));
assertTrue(ObjectUtils.equals(null, null));
assertFalse(ObjectUtils.equals(null, 1));
assertFalse(ObjectUtils.equals(null, ""));
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDiskUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDiskUtilsTest.java | package com.blankj.utilcode.util;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.Serializable;
import static com.blankj.utilcode.util.TestConfig.FILE_SEP;
import static com.blankj.utilcode.util.TestConfig.PATH_CACHE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/05/26
* desc : test CacheDiskUtils
* </pre>
*/
public class CacheDiskUtilsTest extends BaseTest {
private static final String DISK1_PATH = PATH_CACHE + "disk1" + FILE_SEP;
private static final String DISK2_PATH = PATH_CACHE + "disk2" + FILE_SEP;
private static final File DISK1_FILE = new File(DISK1_PATH);
private static final File DISK2_FILE = new File(DISK2_PATH);
private static final CacheDiskUtils CACHE_DISK_UTILS1 = CacheDiskUtils.getInstance(DISK1_FILE);
private static final CacheDiskUtils CACHE_DISK_UTILS2 = CacheDiskUtils.getInstance(DISK2_FILE);
private static final byte[] BYTES = "CacheDiskUtils".getBytes();
private static final String STRING = "CacheDiskUtils";
private static final JSONObject JSON_OBJECT = new JSONObject();
private static final JSONArray JSON_ARRAY = new JSONArray();
private static final ParcelableTest PARCELABLE_TEST = new ParcelableTest("Blankj", "CacheDiskUtils");
private static final SerializableTest SERIALIZABLE_TEST = new SerializableTest("Blankj", "CacheDiskUtils");
private static final Bitmap BITMAP = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565);
private static final Drawable DRAWABLE = new BitmapDrawable(Utils.getApp().getResources(), BITMAP);
static {
try {
JSON_OBJECT.put("class", "CacheDiskUtils");
JSON_OBJECT.put("author", "Blankj");
JSON_ARRAY.put(0, JSON_OBJECT);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Before
public void setUp() {
CACHE_DISK_UTILS1.put("bytes1", BYTES, 60 * CacheDiskUtils.SEC);
CACHE_DISK_UTILS1.put("string1", STRING, 60 * CacheDiskUtils.MIN);
CACHE_DISK_UTILS1.put("jsonObject1", JSON_OBJECT, 24 * CacheDiskUtils.HOUR);
CACHE_DISK_UTILS1.put("jsonArray1", JSON_ARRAY, 365 * CacheDiskUtils.DAY);
CACHE_DISK_UTILS1.put("bitmap1", BITMAP, 60 * CacheDiskUtils.SEC);
CACHE_DISK_UTILS1.put("drawable1", DRAWABLE, 60 * CacheDiskUtils.SEC);
CACHE_DISK_UTILS1.put("parcelable1", PARCELABLE_TEST, 60 * CacheDiskUtils.SEC);
CACHE_DISK_UTILS1.put("serializable1", SERIALIZABLE_TEST, 60 * CacheDiskUtils.SEC);
CACHE_DISK_UTILS2.put("bytes2", BYTES);
CACHE_DISK_UTILS2.put("string2", STRING);
CACHE_DISK_UTILS2.put("jsonObject2", JSON_OBJECT);
CACHE_DISK_UTILS2.put("jsonArray2", JSON_ARRAY);
CACHE_DISK_UTILS2.put("bitmap2", BITMAP);
CACHE_DISK_UTILS2.put("drawable2", DRAWABLE);
CACHE_DISK_UTILS2.put("parcelable2", PARCELABLE_TEST);
CACHE_DISK_UTILS2.put("serializable2", SERIALIZABLE_TEST);
}
@Test
public void getBytes() {
assertEquals(STRING, new String(CACHE_DISK_UTILS1.getBytes("bytes1")));
assertEquals(STRING, new String(CACHE_DISK_UTILS1.getBytes("bytes1", null)));
assertNull(CACHE_DISK_UTILS1.getBytes("bytes2", null));
assertEquals(STRING, new String(CACHE_DISK_UTILS2.getBytes("bytes2")));
assertEquals(STRING, new String(CACHE_DISK_UTILS2.getBytes("bytes2", null)));
assertNull(CACHE_DISK_UTILS2.getBytes("bytes1", null));
}
@Test
public void getString() {
assertEquals(STRING, CACHE_DISK_UTILS1.getString("string1"));
assertEquals(STRING, CACHE_DISK_UTILS1.getString("string1", null));
assertNull(CACHE_DISK_UTILS1.getString("string2", null));
assertEquals(STRING, CACHE_DISK_UTILS2.getString("string2"));
assertEquals(STRING, CACHE_DISK_UTILS2.getString("string2", null));
assertNull(CACHE_DISK_UTILS2.getString("string1", null));
}
@Test
public void getJSONObject() {
assertEquals(JSON_OBJECT.toString(), CACHE_DISK_UTILS1.getJSONObject("jsonObject1").toString());
assertEquals(JSON_OBJECT.toString(), CACHE_DISK_UTILS1.getJSONObject("jsonObject1", null).toString());
assertNull(CACHE_DISK_UTILS1.getJSONObject("jsonObject2", null));
assertEquals(JSON_OBJECT.toString(), CACHE_DISK_UTILS2.getJSONObject("jsonObject2").toString());
assertEquals(JSON_OBJECT.toString(), CACHE_DISK_UTILS2.getJSONObject("jsonObject2", null).toString());
assertNull(CACHE_DISK_UTILS2.getJSONObject("jsonObject1", null));
}
@Test
public void getJSONArray() {
assertEquals(JSON_ARRAY.toString(), CACHE_DISK_UTILS1.getJSONArray("jsonArray1").toString());
assertEquals(JSON_ARRAY.toString(), CACHE_DISK_UTILS1.getJSONArray("jsonArray1", null).toString());
assertNull(CACHE_DISK_UTILS1.getJSONArray("jsonArray2", null));
assertEquals(JSON_ARRAY.toString(), CACHE_DISK_UTILS2.getJSONArray("jsonArray2").toString());
assertEquals(JSON_ARRAY.toString(), CACHE_DISK_UTILS2.getJSONArray("jsonArray2", null).toString());
assertNull(CACHE_DISK_UTILS2.getJSONArray("jsonArray1", null));
}
@Test
public void getBitmap() {
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.bitmap2Bytes(CACHE_DISK_UTILS1.getBitmap("bitmap1"), Bitmap.CompressFormat.PNG, 100)
);
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.bitmap2Bytes(CACHE_DISK_UTILS1.getBitmap("bitmap1", null), Bitmap.CompressFormat.PNG, 100)
);
assertNull(CACHE_DISK_UTILS1.getBitmap("bitmap2", null));
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.bitmap2Bytes(CACHE_DISK_UTILS2.getBitmap("bitmap2"), Bitmap.CompressFormat.PNG, 100)
);
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.bitmap2Bytes(CACHE_DISK_UTILS2.getBitmap("bitmap2", null), Bitmap.CompressFormat.PNG, 100)
);
assertNull(CACHE_DISK_UTILS2.getBitmap("bitmap1", null));
}
@Test
public void getDrawable() {
String bitmapString = "Bitmap (100 x 100) compressed as PNG with quality 100";
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.drawable2Bytes(CACHE_DISK_UTILS1.getDrawable("drawable1"), Bitmap.CompressFormat.PNG, 100)
);
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.drawable2Bytes(CACHE_DISK_UTILS1.getDrawable("drawable1", null), Bitmap.CompressFormat.PNG, 100)
);
assertNull(CACHE_DISK_UTILS1.getDrawable("drawable2", null));
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.drawable2Bytes(CACHE_DISK_UTILS2.getDrawable("drawable2"), Bitmap.CompressFormat.PNG, 100)
);
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.drawable2Bytes(CACHE_DISK_UTILS2.getDrawable("drawable2", null), Bitmap.CompressFormat.PNG, 100)
);
assertNull(CACHE_DISK_UTILS2.getDrawable("drawable1", null));
}
@Test
public void getParcel() {
assertEquals(PARCELABLE_TEST, CACHE_DISK_UTILS1.getParcelable("parcelable1", ParcelableTest.CREATOR));
assertEquals(PARCELABLE_TEST, CACHE_DISK_UTILS1.getParcelable("parcelable1", ParcelableTest.CREATOR, null));
assertNull(CACHE_DISK_UTILS1.getParcelable("parcelable2", ParcelableTest.CREATOR, null));
assertEquals(PARCELABLE_TEST, CACHE_DISK_UTILS2.getParcelable("parcelable2", ParcelableTest.CREATOR));
assertEquals(PARCELABLE_TEST, CACHE_DISK_UTILS2.getParcelable("parcelable2", ParcelableTest.CREATOR, null));
assertNull(CACHE_DISK_UTILS2.getParcelable("parcelable1", ParcelableTest.CREATOR, null));
}
@Test
public void getSerializable() {
assertEquals(SERIALIZABLE_TEST, CACHE_DISK_UTILS1.getSerializable("serializable1"));
assertEquals(SERIALIZABLE_TEST, CACHE_DISK_UTILS1.getSerializable("serializable1", null));
assertNull(CACHE_DISK_UTILS1.getSerializable("parcelable2", null));
assertEquals(SERIALIZABLE_TEST, CACHE_DISK_UTILS2.getSerializable("serializable2"));
assertEquals(SERIALIZABLE_TEST, CACHE_DISK_UTILS2.getSerializable("serializable2", null));
assertNull(CACHE_DISK_UTILS2.getSerializable("parcelable1", null));
}
@Test
public void getCacheSize() {
System.out.println(FileUtils.getLength(DISK1_FILE));
assertEquals(FileUtils.getLength(DISK1_FILE), CACHE_DISK_UTILS1.getCacheSize());
System.out.println(FileUtils.getLength(DISK2_FILE));
assertEquals(FileUtils.getLength(DISK2_FILE), CACHE_DISK_UTILS2.getCacheSize());
}
@Test
public void getCacheCount() {
assertEquals(8, CACHE_DISK_UTILS1.getCacheCount());
assertEquals(8, CACHE_DISK_UTILS2.getCacheCount());
}
@Test
public void remove() {
assertNotNull(CACHE_DISK_UTILS1.getString("string1"));
assertTrue(CACHE_DISK_UTILS1.remove("string1"));
assertNull(CACHE_DISK_UTILS1.getString("string1"));
assertNotNull(CACHE_DISK_UTILS2.getString("string2"));
CACHE_DISK_UTILS2.remove("string2");
assertNull(CACHE_DISK_UTILS2.getString("string2"));
}
@Test
public void clear() {
assertNotNull(CACHE_DISK_UTILS1.getBytes("bytes1"));
assertNotNull(CACHE_DISK_UTILS1.getString("string1"));
assertNotNull(CACHE_DISK_UTILS1.getJSONObject("jsonObject1"));
assertNotNull(CACHE_DISK_UTILS1.getJSONArray("jsonArray1"));
assertNotNull(CACHE_DISK_UTILS1.getBitmap("bitmap1"));
assertNotNull(CACHE_DISK_UTILS1.getDrawable("drawable1"));
assertNotNull(CACHE_DISK_UTILS1.getParcelable("parcelable1", ParcelableTest.CREATOR));
assertNotNull(CACHE_DISK_UTILS1.getSerializable("serializable1"));
CACHE_DISK_UTILS1.clear();
assertNull(CACHE_DISK_UTILS1.getBytes("bytes1"));
assertNull(CACHE_DISK_UTILS1.getString("string1"));
assertNull(CACHE_DISK_UTILS1.getJSONObject("jsonObject1"));
assertNull(CACHE_DISK_UTILS1.getJSONArray("jsonArray1"));
assertNull(CACHE_DISK_UTILS1.getBitmap("bitmap1"));
assertNull(CACHE_DISK_UTILS1.getDrawable("drawable1"));
assertNull(CACHE_DISK_UTILS1.getParcelable("parcelable1", ParcelableTest.CREATOR));
assertNull(CACHE_DISK_UTILS1.getSerializable("serializable1"));
assertEquals(0, CACHE_DISK_UTILS1.getCacheSize());
assertEquals(0, CACHE_DISK_UTILS1.getCacheCount());
assertNotNull(CACHE_DISK_UTILS2.getBytes("bytes2"));
assertNotNull(CACHE_DISK_UTILS2.getString("string2"));
assertNotNull(CACHE_DISK_UTILS2.getJSONObject("jsonObject2"));
assertNotNull(CACHE_DISK_UTILS2.getJSONArray("jsonArray2"));
assertNotNull(CACHE_DISK_UTILS2.getBitmap("bitmap2"));
assertNotNull(CACHE_DISK_UTILS2.getDrawable("drawable2"));
assertNotNull(CACHE_DISK_UTILS2.getParcelable("parcelable2", ParcelableTest.CREATOR));
assertNotNull(CACHE_DISK_UTILS2.getSerializable("serializable2"));
CACHE_DISK_UTILS2.clear();
assertNull(CACHE_DISK_UTILS2.getBytes("bytes2"));
assertNull(CACHE_DISK_UTILS2.getString("string2"));
assertNull(CACHE_DISK_UTILS2.getJSONObject("jsonObject2"));
assertNull(CACHE_DISK_UTILS2.getJSONArray("jsonArray2"));
assertNull(CACHE_DISK_UTILS2.getBitmap("bitmap2"));
assertNull(CACHE_DISK_UTILS2.getDrawable("drawable2"));
assertNull(CACHE_DISK_UTILS2.getParcelable("parcelable2", ParcelableTest.CREATOR));
assertNull(CACHE_DISK_UTILS2.getSerializable("serializable2"));
assertEquals(0, CACHE_DISK_UTILS2.getCacheSize());
assertEquals(0, CACHE_DISK_UTILS2.getCacheCount());
}
@After
public void tearDown() {
CACHE_DISK_UTILS1.clear();
CACHE_DISK_UTILS2.clear();
}
static class ParcelableTest implements Parcelable {
String author;
String className;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
ParcelableTest(String author, String className) {
this.author = author;
this.className = className;
}
ParcelableTest(Parcel in) {
author = in.readString();
className = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(author);
dest.writeString(className);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<ParcelableTest> CREATOR = new Creator<ParcelableTest>() {
@Override
public ParcelableTest createFromParcel(Parcel in) {
return new ParcelableTest(in);
}
@Override
public ParcelableTest[] newArray(int size) {
return new ParcelableTest[size];
}
};
@Override
public boolean equals(Object obj) {
return obj instanceof ParcelableTest
&& ((ParcelableTest) obj).author.equals(author)
&& ((ParcelableTest) obj).className.equals(className);
}
}
static class SerializableTest implements Serializable {
private static final long serialVersionUID = -5806706668736895024L;
String author;
String className;
SerializableTest(String author, String className) {
this.author = author;
this.className = className;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
@Override
public boolean equals(Object obj) {
return obj instanceof SerializableTest
&& ((SerializableTest) obj).author.equals(author)
&& ((SerializableTest) obj).className.equals(className);
}
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/FileIOUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/FileIOUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.After;
import org.junit.Test;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import static com.blankj.utilcode.util.TestConfig.PATH_TEMP;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/05/24
* desc : test FileIOUtils
* </pre>
*/
public class FileIOUtilsTest extends BaseTest {
@Test
public void writeFileFromIS() throws Exception {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
sb.append(String.format("%5dFileIOUtilsTest\n", i));
}
InputStream is = ConvertUtils.string2InputStream(sb.toString(), "UTF-8");
FileIOUtils.writeFileFromIS(PATH_TEMP + "writeFileFromIS.txt", is, new FileIOUtils.OnProgressUpdateListener() {
@Override
public void onProgressUpdate(double progress) {
System.out.println(String.format("%.2f", progress));
}
});
}
@Test
public void writeFileFromBytesByStream() throws Exception {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
sb.append(String.format("%5dFileIOUtilsTest\n", i));
}
byte[] bytes = sb.toString().getBytes(StandardCharsets.UTF_8);
FileIOUtils.writeFileFromBytesByStream(PATH_TEMP + "writeFileFromBytesByStream.txt", bytes, new FileIOUtils.OnProgressUpdateListener() {
@Override
public void onProgressUpdate(double progress) {
System.out.println(String.format("%.2f", progress));
}
});
}
@Test
public void writeFileFromString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i).append("FileIOUtilsTest\n");
}
FileIOUtils.writeFileFromString(PATH_TEMP + "writeFileFromString.txt", sb.toString());
}
@Test
public void readFile2List() {
writeFileFromString();
for (String s : FileIOUtils.readFile2List(PATH_TEMP + "writeFileFromString.txt")) {
System.out.println(s);
}
}
@Test
public void readFile2String() {
writeFileFromString();
System.out.println(FileIOUtils.readFile2String(PATH_TEMP + "writeFileFromString.txt"));
}
@Test
public void readFile2Bytes() throws Exception {
writeFileFromBytesByStream();
FileIOUtils.readFile2BytesByStream(PATH_TEMP + "writeFileFromIS.txt", new FileIOUtils.OnProgressUpdateListener() {
@Override
public void onProgressUpdate(double progress) {
System.out.println(String.format("%.2f", progress));
}
});
}
@After
public void tearDown() {
FileUtils.deleteAllInDir(PATH_TEMP);
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheMemoryStaticUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheMemoryStaticUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/01/04
* desc : test CacheMemoryStaticUtils
* </pre>
*/
public class CacheMemoryStaticUtilsTest extends BaseTest {
private CacheMemoryUtils mCacheMemoryUtils = CacheMemoryUtils.getInstance(3);
@Before
public void setUp() {
for (int i = 0; i < 10; i++) {
CacheMemoryStaticUtils.put(String.valueOf(i), i);
}
for (int i = 0; i < 10; i++) {
CacheMemoryStaticUtils.put(String.valueOf(i), i, mCacheMemoryUtils);
}
}
@Test
public void get() {
for (int i = 0; i < 10; i++) {
assertEquals(i, CacheMemoryStaticUtils.get(String.valueOf(i)));
}
for (int i = 0; i < 10; i++) {
if (i < 7) {
assertNull(CacheMemoryStaticUtils.get(String.valueOf(i), mCacheMemoryUtils));
} else {
assertEquals(i, CacheMemoryStaticUtils.get(String.valueOf(i), mCacheMemoryUtils));
}
}
}
@Test
public void getExpired() throws Exception {
CacheMemoryStaticUtils.put("10", 10, 2 * CacheMemoryUtils.SEC);
assertEquals(10, CacheMemoryStaticUtils.get("10"));
Thread.sleep(1500);
assertEquals(10, CacheMemoryStaticUtils.get("10"));
Thread.sleep(1500);
assertNull(CacheMemoryStaticUtils.get("10"));
}
@Test
public void getDefault() {
assertNull(CacheMemoryStaticUtils.get("10"));
assertEquals("10", CacheMemoryStaticUtils.get("10", "10"));
}
@Test
public void getCacheCount() {
assertEquals(10, CacheMemoryStaticUtils.getCacheCount());
assertEquals(3, CacheMemoryStaticUtils.getCacheCount(mCacheMemoryUtils));
}
@Test
public void remove() {
assertEquals(0, CacheMemoryStaticUtils.remove("0"));
assertNull(CacheMemoryStaticUtils.get("0"));
assertNull(CacheMemoryStaticUtils.remove("0"));
}
@Test
public void clear() {
CacheMemoryStaticUtils.clear();
CacheMemoryStaticUtils.clear(mCacheMemoryUtils);
for (int i = 0; i < 10; i++) {
assertNull(CacheMemoryStaticUtils.get(String.valueOf(i)));
}
for (int i = 0; i < 10; i++) {
assertNull(CacheMemoryStaticUtils.get(String.valueOf(i), mCacheMemoryUtils));
}
assertEquals(0, CacheMemoryStaticUtils.getCacheCount());
assertEquals(0, CacheMemoryStaticUtils.getCacheCount(mCacheMemoryUtils));
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/CollectionUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/CollectionUtilsTest.java | package com.blankj.utilcode.util;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/08/12
* desc : test CollectionUtils
* </pre>
*/
public class CollectionUtilsTest extends BaseTest {
@Test
public void union() {
ArrayList<String> l0 = CollectionUtils.newArrayList("00", "01", "02");
ArrayList<String> l1 = CollectionUtils.newArrayList("00", "11", "12");
Collection unionNullNull = CollectionUtils.union(null, null);
Collection unionL0Null = CollectionUtils.union(l0, null);
Collection unionNullL1 = CollectionUtils.union(null, l1);
Collection unionL0L1 = CollectionUtils.union(l0, l1);
System.out.println(unionNullNull);
System.out.println(unionL0Null);
System.out.println(unionNullL1);
System.out.println(unionL0L1);
Assert.assertNotSame(l0, unionL0Null);
Assert.assertNotSame(l1, unionNullL1);
}
@Test
public void intersection() {
ArrayList<String> l0 = CollectionUtils.newArrayList("00", "01", "02");
ArrayList<String> l1 = CollectionUtils.newArrayList("00", "11", "12");
Collection intersectionNullNull = CollectionUtils.intersection(null, null);
Collection intersectionL0Null = CollectionUtils.intersection(l0, null);
Collection intersectionNullL1 = CollectionUtils.intersection(null, l1);
Collection intersectionL0L1 = CollectionUtils.intersection(l0, l1);
System.out.println(intersectionNullNull);
System.out.println(intersectionL0Null);
System.out.println(intersectionNullL1);
System.out.println(intersectionL0L1);
}
@Test
public void disjunction() {
ArrayList<String> l0 = CollectionUtils.newArrayList("00", "01", "02");
ArrayList<String> l1 = CollectionUtils.newArrayList("00", "11", "12");
Collection disjunctionNullNull = CollectionUtils.disjunction(null, null);
Collection disjunctionL0Null = CollectionUtils.disjunction(l0, null);
Collection disjunctionNullL1 = CollectionUtils.disjunction(null, l1);
Collection disjunctionL0L1 = CollectionUtils.disjunction(l0, l1);
System.out.println(disjunctionNullNull);
System.out.println(disjunctionL0Null);
System.out.println(disjunctionNullL1);
System.out.println(disjunctionL0L1);
Assert.assertNotSame(l0, disjunctionL0Null);
Assert.assertNotSame(l1, disjunctionNullL1);
}
@Test
public void subtract() {
ArrayList<String> l0 = CollectionUtils.newArrayList("00", "01", "02");
ArrayList<String> l1 = CollectionUtils.newArrayList("00", "11", "12");
Collection subtractNullNull = CollectionUtils.subtract(null, null);
Collection subtractL0Null = CollectionUtils.subtract(l0, null);
Collection subtractNullL1 = CollectionUtils.subtract(null, l1);
Collection subtractL0L1 = CollectionUtils.subtract(l0, l1);
System.out.println(subtractNullNull);
System.out.println(subtractL0Null);
System.out.println(subtractNullL1);
System.out.println(subtractL0L1);
Assert.assertNotSame(l0, subtractL0Null);
}
@Test
public void containsAny() {
ArrayList<String> l0 = CollectionUtils.newArrayList("00", "01", "02");
ArrayList<String> l1 = CollectionUtils.newArrayList("00", "11", "12");
Assert.assertFalse(CollectionUtils.containsAny(null, null));
Assert.assertFalse(CollectionUtils.containsAny(l0, null));
Assert.assertFalse(CollectionUtils.containsAny(null, l1));
Assert.assertTrue(CollectionUtils.containsAny(l0, l1));
}
@Test
public void getCardinalityMap() {
System.out.println(CollectionUtils.getCardinalityMap(null));
ArrayList<String> l0 = CollectionUtils.newArrayList("0", "0", "1", "1", "2");
System.out.println(CollectionUtils.getCardinalityMap(l0));
}
@Test
public void isSubCollection() {
ArrayList<String> l0 = CollectionUtils.newArrayList("0", "1", "2");
ArrayList<String> l1 = CollectionUtils.newArrayList("0", "0", "1", "1", "2");
Assert.assertFalse(CollectionUtils.isSubCollection(null, null));
Assert.assertFalse(CollectionUtils.isSubCollection(l0, null));
Assert.assertFalse(CollectionUtils.isSubCollection(null, l0));
Assert.assertTrue(CollectionUtils.isSubCollection(l0, l1));
Assert.assertTrue(CollectionUtils.isSubCollection(l0, l0));
Assert.assertFalse(CollectionUtils.isSubCollection(l1, l0));
}
@Test
public void isProperSubCollection() {
ArrayList<String> l0 = CollectionUtils.newArrayList("0", "1", "2");
ArrayList<String> l1 = CollectionUtils.newArrayList("0", "0", "1", "1", "2");
Assert.assertFalse(CollectionUtils.isProperSubCollection(null, null));
Assert.assertFalse(CollectionUtils.isProperSubCollection(l0, null));
Assert.assertFalse(CollectionUtils.isProperSubCollection(null, l0));
Assert.assertTrue(CollectionUtils.isProperSubCollection(l0, l1));
Assert.assertFalse(CollectionUtils.isProperSubCollection(l0, l0));
Assert.assertFalse(CollectionUtils.isProperSubCollection(l1, l0));
}
@Test
public void isEqualCollection() {
ArrayList<String> l0 = CollectionUtils.newArrayList("0", "1", "2");
ArrayList<String> l1 = CollectionUtils.newArrayList("0", "0", "1", "1", "2");
Assert.assertFalse(CollectionUtils.isEqualCollection(null, null));
Assert.assertFalse(CollectionUtils.isEqualCollection(l0, null));
Assert.assertFalse(CollectionUtils.isEqualCollection(null, l0));
Assert.assertTrue(CollectionUtils.isEqualCollection(l0, l0));
Assert.assertFalse(CollectionUtils.isEqualCollection(l0, l1));
}
@Test
public void cardinality() {
ArrayList<String> list = CollectionUtils.newArrayList("0", "1", "1", "2");
Assert.assertEquals(0, CollectionUtils.cardinality(null, null));
Assert.assertEquals(0, CollectionUtils.cardinality(null, list));
list.add(null);
Assert.assertEquals(1, CollectionUtils.cardinality(null, list));
Assert.assertEquals(2, CollectionUtils.cardinality("1", list));
}
@Test
public void find() {
ArrayList<String> list = CollectionUtils.newArrayList("0", "1", "1", "2");
Assert.assertNull(CollectionUtils.find(null, null));
Assert.assertNull(CollectionUtils.find(list, null));
Assert.assertNull(CollectionUtils.find(null, new CollectionUtils.Predicate<String>() {
@Override
public boolean evaluate(String item) {
return true;
}
}));
Assert.assertEquals("1", CollectionUtils.find(list, new CollectionUtils.Predicate<String>() {
@Override
public boolean evaluate(String item) {
return "1".equals(item);
}
}));
}
@Test
public void forAllDo() {
ArrayList<String> list = CollectionUtils.newArrayList("0", "1", "1", "2");
CollectionUtils.forAllDo(null, null);
CollectionUtils.forAllDo(list, null);
CollectionUtils.forAllDo(null, new CollectionUtils.Closure<Object>() {
@Override
public void execute(int index, Object item) {
System.out.println(index + ": " + index);
}
});
CollectionUtils.forAllDo(list, new CollectionUtils.Closure<String>() {
@Override
public void execute(int index, String item) {
System.out.println(index + ": " + index);
}
});
}
@Test
public void filter() {
ArrayList<Integer> l0 = null;
ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3);
CollectionUtils.filter(l0, null);
Assert.assertNull(l0);
CollectionUtils.filter(l0, new CollectionUtils.Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return item > 1;
}
});
Assert.assertNull(l0);
CollectionUtils.filter(l1, null);
Assert.assertEquals(l1, l1);
CollectionUtils.filter(l1, new CollectionUtils.Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return item > 1;
}
});
Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList(2, 3), l1));
}
@Test
public void select() {
ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertEquals(0, CollectionUtils.select(null, null).size());
Assert.assertEquals(0, CollectionUtils.select(list, null).size());
Assert.assertEquals(0, CollectionUtils.select(null, new CollectionUtils.Predicate<Object>() {
@Override
public boolean evaluate(Object item) {
return true;
}
}).size());
Assert.assertTrue(CollectionUtils.isEqualCollection(
CollectionUtils.newArrayList(2, 3),
CollectionUtils.select(list, new CollectionUtils.Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return item > 1;
}
})));
Collection<Integer> list1 = CollectionUtils.select(list, new CollectionUtils.Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return true;
}
});
Assert.assertTrue(CollectionUtils.isEqualCollection(list, list1));
Assert.assertNotSame(list, list1);
}
@Test
public void selectRejected() {
ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertEquals(0, CollectionUtils.selectRejected(null, null).size());
Assert.assertEquals(0, CollectionUtils.selectRejected(list, null).size());
Assert.assertEquals(0, CollectionUtils.selectRejected(null, new CollectionUtils.Predicate<Object>() {
@Override
public boolean evaluate(Object item) {
return true;
}
}).size());
Assert.assertTrue(CollectionUtils.isEqualCollection(
CollectionUtils.newArrayList(0, 1),
CollectionUtils.selectRejected(list, new CollectionUtils.Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return item > 1;
}
})));
Collection<Integer> list1 = CollectionUtils.selectRejected(list, new CollectionUtils.Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return false;
}
});
Assert.assertTrue(CollectionUtils.isEqualCollection(list, list1));
Assert.assertNotSame(list, list1);
}
@Test
public void transform() {
ArrayList<Integer> l0 = null;
ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3);
CollectionUtils.transform(l0, null);
Assert.assertNull(l0);
CollectionUtils.transform(l0, new CollectionUtils.Transformer<Integer, Object>() {
@Override
public Object transform(Integer input) {
return "int: " + input;
}
});
Assert.assertNull(l0);
CollectionUtils.transform(l1, null);
Assert.assertEquals(l1, l1);
CollectionUtils.transform(l1, new CollectionUtils.Transformer<Integer, String>() {
@Override
public String transform(Integer input) {
return String.valueOf(input);
}
});
Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList("0", "1", "2", "3"), l1));
}
@Test
public void collect() {
ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertTrue(CollectionUtils.isEmpty(CollectionUtils.collect(null, null)));
Assert.assertTrue(CollectionUtils.isEmpty(CollectionUtils.collect(list, null)));
Assert.assertTrue(CollectionUtils.isEmpty(CollectionUtils.collect(null, new CollectionUtils.Transformer() {
@Override
public Object transform(Object input) {
return null;
}
})));
Assert.assertTrue(CollectionUtils.isEqualCollection(
CollectionUtils.newArrayList("0", "1", "2", "3"),
CollectionUtils.collect(list, new CollectionUtils.Transformer<Integer, String>() {
@Override
public String transform(Integer input) {
return String.valueOf(input);
}
})));
}
@Test
public void countMatches() {
ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertEquals(0, CollectionUtils.countMatches(null, null));
Assert.assertEquals(0, CollectionUtils.countMatches(list, null));
Assert.assertEquals(0, CollectionUtils.countMatches(null, new CollectionUtils.Predicate<Object>() {
@Override
public boolean evaluate(Object item) {
return false;
}
}));
Assert.assertEquals(2, CollectionUtils.countMatches(list, new CollectionUtils.Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return item > 1;
}
}));
}
@Test
public void exists() {
ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertFalse(CollectionUtils.exists(null, null));
Assert.assertFalse(CollectionUtils.exists(list, null));
Assert.assertFalse(CollectionUtils.exists(null, new CollectionUtils.Predicate<Object>() {
@Override
public boolean evaluate(Object item) {
return false;
}
}));
Assert.assertTrue(CollectionUtils.exists(list, new CollectionUtils.Predicate<Integer>() {
@Override
public boolean evaluate(Integer item) {
return item > 1;
}
}));
}
@Test
public void addIgnoreNull() {
ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertFalse(CollectionUtils.addIgnoreNull(null, null));
Assert.assertFalse(CollectionUtils.addIgnoreNull(null, 1));
CollectionUtils.addIgnoreNull(list, null);
Assert.assertEquals(CollectionUtils.newArrayList(0, 1, 2, 3), list);
CollectionUtils.addIgnoreNull(list, 4);
Assert.assertEquals(CollectionUtils.newArrayList(0, 1, 2, 3, 4), list);
}
@Test
public void addAll() {
ArrayList<Integer> l0 = null;
ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3);
CollectionUtils.addAll(l0, (Iterator<Integer>) null);
Assert.assertNull(l0);
CollectionUtils.addAll(l0, (Enumeration<Integer>) null);
Assert.assertNull(l0);
CollectionUtils.addAll(l0, (Integer[]) null);
Assert.assertNull(l0);
CollectionUtils.addAll(l1, (Iterator<Integer>) null);
Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList(0, 1, 2, 3), l1));
CollectionUtils.addAll(l1, (Enumeration<Integer>) null);
Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList(0, 1, 2, 3), l1));
CollectionUtils.addAll(l1, (Integer[]) null);
Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList(0, 1, 2, 3), l1));
CollectionUtils.addAll(l1, CollectionUtils.newArrayList(4, 5).iterator());
Assert.assertTrue(CollectionUtils.isEqualCollection(CollectionUtils.newArrayList(0, 1, 2, 3, 4, 5), l1));
}
@Test
public void get() {
ArrayList<Integer> l0 = null;
ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertNull(CollectionUtils.get(l0, 0));
Assert.assertEquals(0, CollectionUtils.get(l1, 0));
}
@Test
public void size() {
ArrayList<Integer> l0 = null;
ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertEquals(0, CollectionUtils.size(l0));
Assert.assertEquals(4, CollectionUtils.size(l1));
}
@Test
public void sizeIsEmpty() {
ArrayList<Integer> l0 = null;
ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertTrue(CollectionUtils.sizeIsEmpty(l0));
Assert.assertFalse(CollectionUtils.sizeIsEmpty(l1));
}
@Test
public void isEmpty() {
ArrayList<Integer> l0 = null;
ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertTrue(CollectionUtils.isEmpty(l0));
Assert.assertFalse(CollectionUtils.isEmpty(l1));
}
@Test
public void isNotEmpty() {
ArrayList<Integer> l0 = null;
ArrayList<Integer> l1 = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertFalse(CollectionUtils.isNotEmpty(l0));
Assert.assertTrue(CollectionUtils.isNotEmpty(l1));
}
@Test
public void retainAll() {
ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertEquals(0, CollectionUtils.retainAll(null, null).size());
Assert.assertEquals(0, CollectionUtils.retainAll(list, null).size());
Assert.assertEquals(0, CollectionUtils.retainAll(null, list).size());
Assert.assertTrue(CollectionUtils.isEqualCollection(
CollectionUtils.newArrayList(0, 1, 2, 3),
CollectionUtils.retainAll(list, list)
));
Assert.assertTrue(CollectionUtils.isEqualCollection(
CollectionUtils.newArrayList(0, 1),
CollectionUtils.retainAll(list, CollectionUtils.newArrayList(0, 1, 6))
));
}
@Test
public void removeAll() {
ArrayList<Integer> list = CollectionUtils.newArrayList(0, 1, 2, 3);
Assert.assertEquals(0, CollectionUtils.removeAll(null, null).size());
Assert.assertTrue(CollectionUtils.isEqualCollection(
CollectionUtils.newArrayList(0, 1, 2, 3),
CollectionUtils.removeAll(list, null)
));
Assert.assertEquals(0, CollectionUtils.removeAll(null, list).size());
Assert.assertTrue(CollectionUtils.isEqualCollection(
CollectionUtils.newArrayList(2, 3),
CollectionUtils.removeAll(list, CollectionUtils.newArrayList(0, 1, 6))
));
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/BusUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/BusUtilsTest.java | package com.blankj.utilcode.util;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/07/11
* desc :
* </pre>
*/
public class BusUtilsTest extends BaseTest {
private static final String TAG_NO_PARAM = "TagNoParam";
private static final String TAG_ONE_PARAM = "TagOneParam";
private static final String TAG_NO_PARAM_STICKY = "TagNoParamSticky";
private static final String TAG_ONE_PARAM_STICKY = "TagOneParamSticky";
private static final String TAG_IO = "TAG_IO";
private static final String TAG_CPU = "TAG_CPU";
private static final String TAG_CACHED = "TAG_CACHED";
private static final String TAG_SINGLE = "TAG_SINGLE";
@BusUtils.Bus(tag = TAG_NO_PARAM)
public void noParamFun() {
System.out.println("noParam");
}
@BusUtils.Bus(tag = TAG_NO_PARAM)
public void noParamSameTagFun() {
System.out.println("sameTag: noParam");
}
@BusUtils.Bus(tag = TAG_ONE_PARAM)
public void oneParamFun(String param) {
System.out.println(param);
}
@BusUtils.Bus(tag = TAG_NO_PARAM_STICKY, sticky = true)
public void foo() {
System.out.println("foo");
}
@BusUtils.Bus(tag = TAG_ONE_PARAM_STICKY, sticky = true)
public void oneParamStickyFun(Callback callback) {
if (callback != null) {
System.out.println(callback.call());
}
}
@BusUtils.Bus(tag = TAG_IO, threadMode = BusUtils.ThreadMode.IO)
public void ioFun(CountDownLatch latch) {
System.out.println("Thread.currentThread() = " + Thread.currentThread());
latch.countDown();
}
@BusUtils.Bus(tag = TAG_CPU, threadMode = BusUtils.ThreadMode.CPU)
public void cpuFun(CountDownLatch latch) {
System.out.println("Thread.currentThread() = " + Thread.currentThread());
latch.countDown();
}
@BusUtils.Bus(tag = TAG_CACHED, threadMode = BusUtils.ThreadMode.CACHED)
public void cachedFun(CountDownLatch latch) {
System.out.println("Thread.currentThread() = " + Thread.currentThread());
latch.countDown();
}
@BusUtils.Bus(tag = TAG_SINGLE, threadMode = BusUtils.ThreadMode.SINGLE)
public void singleFun(CountDownLatch latch) {
System.out.println("Thread.currentThread() = " + Thread.currentThread());
latch.countDown();
}
@Before
public void setUp() throws Exception {
BusUtils.registerBus4Test(TAG_NO_PARAM, BusUtilsTest.class.getName(), "noParamFun", "", "", false, "POSTING", 0);
BusUtils.registerBus4Test(TAG_ONE_PARAM, BusUtilsTest.class.getName(), "oneParamFun", String.class.getName(), "param", false, "POSTING", 0);
BusUtils.registerBus4Test(TAG_NO_PARAM_STICKY, BusUtilsTest.class.getName(), "noParamStickyFun", "", "", true, "POSTING", 0);
BusUtils.registerBus4Test(TAG_NO_PARAM_STICKY, BusUtilsTest.class.getName(), "foo", "", "", true, "POSTING", 0);
BusUtils.registerBus4Test(TAG_ONE_PARAM_STICKY, BusUtilsTest.class.getName(), "oneParamStickyFun", Callback.class.getName(), "callback", true, "POSTING", 0);
BusUtils.registerBus4Test(TAG_IO, BusUtilsTest.class.getName(), "ioFun", CountDownLatch.class.getName(), "latch", false, "IO", 0);
BusUtils.registerBus4Test(TAG_CPU, BusUtilsTest.class.getName(), "cpuFun", CountDownLatch.class.getName(), "latch", false, "CPU", 0);
BusUtils.registerBus4Test(TAG_CACHED, BusUtilsTest.class.getName(), "cachedFun", CountDownLatch.class.getName(), "latch", false, "CACHED", 0);
BusUtils.registerBus4Test(TAG_SINGLE, BusUtilsTest.class.getName(), "singleFun", CountDownLatch.class.getName(), "latch", false, "SINGLE", 0);
}
@BusUtils.Bus(tag = TAG_NO_PARAM_STICKY, sticky = true)
public void noParamStickyFun() {
// BusUtils.removeSticky(TAG_NO_PARAM_STICKY);
System.out.println("noParamSticky");
}
@Subscribe(sticky = true)
public void eventBusFun(String param) {
System.out.println(param);
}
@Subscribe(sticky = true)
public void eventBusFun1(String param) {
System.out.println("foo");
}
@Test
public void testEventBusSticky() {
EventBus.getDefault().postSticky("test");
System.out.println("----");
BusUtilsTest test = new BusUtilsTest();
EventBus.getDefault().register(new BusUtilsTest());
EventBus.getDefault().register(new BusUtilsTest());
EventBus.getDefault().register(new BusUtilsTest());
System.out.println("----");
EventBus.getDefault().postSticky("test");
EventBus.getDefault().postSticky("test");
}
@Test
public void testSticky() {
BusUtils.postSticky(TAG_NO_PARAM_STICKY);
System.out.println("----");
BusUtilsTest test = new BusUtilsTest();
BusUtils.register(new BusUtilsTest());
BusUtils.register(new BusUtilsTest());
BusUtils.register(new BusUtilsTest());
System.out.println("----");
BusUtils.post(TAG_NO_PARAM_STICKY);
// BusUtils.post(TAG_NO_PARAM_STICKY);
}
@Test
public void testMultiThread() {
final BusUtilsTest test = new BusUtilsTest();
// for (int i = 0; i < 100; i++) {
// new Thread(new Runnable() {
// @Override
// public void run() {
// BusUtils.register(test);
// }
// }).start();
// }
// CountDownLatch countDownLatch = new CountDownLatch(1);
// BusUtils.register(test);
// for (int i = 0; i < 100; i++) {
// new Thread(new Runnable() {
// @Override
// public void run() {
// BusUtils.post(TAG_NO_PARAM);
// }
// }).start();
// }
// try {
// countDownLatch.await(1, TimeUnit.SECONDS);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// BusUtils.unregister(test);
// for (int i = 0; i < 100; i++) {
// new Thread(new Runnable() {
// @Override
// public void run() {
// BusUtils.unregister(test);
// }
// }).start();
// }
// for (int i = 0; i < 100; i++) {
// final int finalI = i;
// new Thread(new Runnable() {
// @Override
// public void run() {
// BusUtils.register(test);
// BusUtils.post(TAG_ONE_PARAM, "" + finalI);
// BusUtils.unregister(test);
// }
// }).start();
// }
}
@Test
public void registerAndUnregister() {
BusUtilsTest test = new BusUtilsTest();
BusUtils.post(TAG_NO_PARAM);
BusUtils.post(TAG_ONE_PARAM, "post to one param fun.");
BusUtils.register(test);
BusUtils.post(TAG_NO_PARAM);
BusUtils.post(TAG_ONE_PARAM, "Post to one param fun.");
BusUtils.unregister(test);
BusUtils.post(TAG_NO_PARAM);
BusUtils.post(TAG_ONE_PARAM, "Post to one param fun.");
}
@Test
public void post() {
BusUtilsTest test0 = new BusUtilsTest();
BusUtilsTest test1 = new BusUtilsTest();
BusUtils.register(test0);
BusUtils.register(test1);
BusUtils.post(TAG_NO_PARAM);
BusUtils.post(TAG_ONE_PARAM, "post to one param fun.");
BusUtils.unregister(test0);
BusUtils.unregister(test1);
}
@Test
public void postSticky() {
System.out.println("-----not sticky bus postSticky will be failed.-----");
BusUtils.postSticky(TAG_NO_PARAM);
BusUtils.postSticky(TAG_ONE_PARAM, "post to one param fun.");
System.out.println("\n-----sticky bus postSticky will be successful.-----");
BusUtils.postSticky(TAG_NO_PARAM_STICKY);
BusUtils.postSticky(TAG_ONE_PARAM_STICKY, new Callback() {
@Override
public String call() {
return "post to one param sticky fun.";
}
});
BusUtilsTest test = new BusUtilsTest();
System.out.println("\n-----register.-----");
BusUtils.register(test);
System.out.println("\n-----sticky post.-----");
BusUtils.postSticky(TAG_NO_PARAM);
BusUtils.postSticky(TAG_ONE_PARAM, "post to one param fun.");
BusUtils.postSticky(TAG_NO_PARAM_STICKY);
BusUtils.postSticky(TAG_ONE_PARAM_STICKY, new Callback() {
@Override
public String call() {
return "post to one param sticky fun.";
}
});
BusUtils.removeSticky(TAG_NO_PARAM_STICKY);
BusUtils.removeSticky(TAG_ONE_PARAM_STICKY);
BusUtils.unregister(test);
}
@Test
public void removeSticky() {
BusUtils.postSticky(TAG_NO_PARAM_STICKY);
BusUtils.postSticky(TAG_ONE_PARAM_STICKY, new Callback() {
@Override
public String call() {
return "post to one param sticky fun.";
}
});
BusUtilsTest test = new BusUtilsTest();
System.out.println("-----register.-----");
BusUtils.register(test);
BusUtils.unregister(test);
System.out.println("\n-----register.-----");
BusUtils.register(test);
System.out.println("\n-----remove sticky bus.-----");
BusUtils.removeSticky(TAG_NO_PARAM_STICKY);
BusUtils.removeSticky(TAG_ONE_PARAM_STICKY);
BusUtils.unregister(test);
System.out.println("\n-----register.-----");
BusUtils.register(test);
BusUtils.unregister(test);
}
@Test
public void testThreadMode() throws InterruptedException {
BusUtilsTest test = new BusUtilsTest();
CountDownLatch latch = new CountDownLatch(4);
BusUtils.register(test);
BusUtils.post(TAG_IO, latch);
BusUtils.post(TAG_CPU, latch);
BusUtils.post(TAG_CACHED, latch);
BusUtils.post(TAG_SINGLE, latch);
latch.await();
BusUtils.unregister(test);
}
@Test
public void toString_() {
System.out.println("BusUtils.toString_() = " + BusUtils.toString_());
}
@Test
public void testBase() {
BusUtils.registerBus4Test("base", BaseTest.class.getName(), "noParamFun", "int", "i", false, "POSTING", 0);
BaseTest t = new BusUtilsTest();
BusUtils.register(t);
BusUtils.post("base", 1);
BusUtils.unregister(t);
}
@Test
public void testSameTag() {
BusUtils.registerBus4Test(TAG_NO_PARAM, BusUtilsTest.class.getName(), "noParamSameTagFun", "", "", false, "POSTING", 2);
BusUtilsTest test = new BusUtilsTest();
BusUtils.register(test);
BusUtils.post(TAG_NO_PARAM);
BusUtils.unregister(test);
}
public interface Callback {
String call();
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDoubleUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/CacheDoubleUtilsTest.java | package com.blankj.utilcode.util;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.Serializable;
import static com.blankj.utilcode.util.TestConfig.FILE_SEP;
import static com.blankj.utilcode.util.TestConfig.PATH_CACHE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/06/13
* desc : test CacheDoubleUtils
* </pre>
*/
public class CacheDoubleUtilsTest extends BaseTest {
private static final String CACHE_PATH = PATH_CACHE + "double" + FILE_SEP;
private static final File CACHE_FILE = new File(CACHE_PATH);
private static final byte[] BYTES = "CacheDoubleUtils".getBytes();
private static final String STRING = "CacheDoubleUtils";
private static final JSONObject JSON_OBJECT = new JSONObject();
private static final JSONArray JSON_ARRAY = new JSONArray();
private static final ParcelableTest PARCELABLE_TEST = new ParcelableTest("Blankj", "CacheDoubleUtils");
private static final SerializableTest SERIALIZABLE_TEST = new SerializableTest("Blankj", "CacheDoubleUtils");
private static final Bitmap BITMAP = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565);
private static final Drawable DRAWABLE = new BitmapDrawable(Utils.getApp().getResources(), BITMAP);
private static final CacheMemoryUtils CACHE_MEMORY_UTILS = CacheMemoryUtils.getInstance();
private static final CacheDiskUtils CACHE_DISK_UTILS = CacheDiskUtils.getInstance(CACHE_FILE);
private static final CacheDoubleUtils CACHE_DOUBLE_UTILS = CacheDoubleUtils.getInstance(CACHE_MEMORY_UTILS, CACHE_DISK_UTILS);
static {
try {
JSON_OBJECT.put("class", "CacheDiskUtils");
JSON_OBJECT.put("author", "Blankj");
JSON_ARRAY.put(0, JSON_OBJECT);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Before
public void setUp() {
CACHE_DOUBLE_UTILS.put("bytes", BYTES);
CACHE_DOUBLE_UTILS.put("string", STRING);
CACHE_DOUBLE_UTILS.put("jsonObject", JSON_OBJECT);
CACHE_DOUBLE_UTILS.put("jsonArray", JSON_ARRAY);
CACHE_DOUBLE_UTILS.put("bitmap", BITMAP);
CACHE_DOUBLE_UTILS.put("drawable", DRAWABLE);
CACHE_DOUBLE_UTILS.put("parcelable", PARCELABLE_TEST);
CACHE_DOUBLE_UTILS.put("serializable", SERIALIZABLE_TEST);
}
@Test
public void getBytes() {
assertEquals(STRING, new String(CACHE_DOUBLE_UTILS.getBytes("bytes")));
CACHE_MEMORY_UTILS.remove("bytes");
assertEquals(STRING, new String(CACHE_DOUBLE_UTILS.getBytes("bytes")));
CACHE_DISK_UTILS.remove("bytes");
assertNull(CACHE_DOUBLE_UTILS.getBytes("bytes"));
}
@Test
public void getString() {
assertEquals(STRING, CACHE_DOUBLE_UTILS.getString("string"));
CACHE_MEMORY_UTILS.remove("string");
assertEquals(STRING, CACHE_DOUBLE_UTILS.getString("string"));
CACHE_DISK_UTILS.remove("string");
assertNull(CACHE_DOUBLE_UTILS.getString("string"));
}
@Test
public void getJSONObject() {
assertEquals(JSON_OBJECT.toString(), CACHE_DOUBLE_UTILS.getJSONObject("jsonObject").toString());
CACHE_MEMORY_UTILS.remove("jsonObject");
assertEquals(JSON_OBJECT.toString(), CACHE_DOUBLE_UTILS.getJSONObject("jsonObject").toString());
CACHE_DISK_UTILS.remove("jsonObject");
assertNull(CACHE_DOUBLE_UTILS.getJSONObject("jsonObject"));
}
@Test
public void getJSONArray() {
assertEquals(JSON_ARRAY.toString(), CACHE_DOUBLE_UTILS.getJSONArray("jsonArray").toString());
CACHE_MEMORY_UTILS.remove("jsonArray");
assertEquals(JSON_ARRAY.toString(), CACHE_DOUBLE_UTILS.getJSONArray("jsonArray").toString());
CACHE_DISK_UTILS.remove("jsonArray");
assertNull(CACHE_DOUBLE_UTILS.getJSONArray("jsonArray"));
}
@Test
public void getBitmap() {
String bitmapString = "Bitmap (100 x 100) compressed as PNG with quality 100";
assertEquals(BITMAP, CACHE_DOUBLE_UTILS.getBitmap("bitmap"));
CACHE_MEMORY_UTILS.remove("bitmap");
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.bitmap2Bytes(CACHE_DOUBLE_UTILS.getBitmap("bitmap"), Bitmap.CompressFormat.PNG, 100)
);
CACHE_DISK_UTILS.remove("bitmap");
assertNull(CACHE_DOUBLE_UTILS.getBitmap("bitmap"));
}
@Test
public void getDrawable() {
String bitmapString = "Bitmap (100 x 100) compressed as PNG with quality 100";
assertEquals(DRAWABLE, CACHE_DOUBLE_UTILS.getDrawable("drawable"));
CACHE_MEMORY_UTILS.remove("drawable");
assertArrayEquals(
ImageUtils.bitmap2Bytes(BITMAP, Bitmap.CompressFormat.PNG, 100),
ImageUtils.drawable2Bytes(CACHE_DOUBLE_UTILS.getDrawable("drawable"), Bitmap.CompressFormat.PNG, 100)
);
CACHE_DISK_UTILS.remove("drawable");
assertNull(CACHE_DOUBLE_UTILS.getDrawable("drawable"));
}
@Test
public void getParcel() {
assertEquals(PARCELABLE_TEST, CACHE_DOUBLE_UTILS.getParcelable("parcelable", ParcelableTest.CREATOR));
CACHE_MEMORY_UTILS.remove("parcelable");
assertEquals(PARCELABLE_TEST, CACHE_DOUBLE_UTILS.getParcelable("parcelable", ParcelableTest.CREATOR));
CACHE_DISK_UTILS.remove("parcelable");
assertNull(CACHE_DOUBLE_UTILS.getParcelable("parcelable", ParcelableTest.CREATOR));
}
@Test
public void getSerializable() {
assertEquals(SERIALIZABLE_TEST, CACHE_DOUBLE_UTILS.getSerializable("serializable"));
CACHE_MEMORY_UTILS.remove("serializable");
assertEquals(SERIALIZABLE_TEST, CACHE_DOUBLE_UTILS.getSerializable("serializable"));
CACHE_DISK_UTILS.remove("serializable");
assertNull(CACHE_DOUBLE_UTILS.getSerializable("serializable"));
}
@Test
public void getCacheDiskSize() {
assertEquals(FileUtils.getLength(CACHE_FILE), CACHE_DOUBLE_UTILS.getCacheDiskSize());
}
@Test
public void getCacheDiskCount() {
assertEquals(8, CACHE_DOUBLE_UTILS.getCacheDiskCount());
}
@Test
public void getCacheMemoryCount() {
assertEquals(8, CACHE_DOUBLE_UTILS.getCacheMemoryCount());
}
@Test
public void remove() {
assertNotNull(CACHE_DOUBLE_UTILS.getString("string"));
CACHE_DOUBLE_UTILS.remove("string");
assertNull(CACHE_DOUBLE_UTILS.getString("string"));
}
@Test
public void clear() {
assertNotNull(CACHE_DOUBLE_UTILS.getBytes("bytes"));
assertNotNull(CACHE_DOUBLE_UTILS.getString("string"));
assertNotNull(CACHE_DOUBLE_UTILS.getJSONObject("jsonObject"));
assertNotNull(CACHE_DOUBLE_UTILS.getJSONArray("jsonArray"));
assertNotNull(CACHE_DOUBLE_UTILS.getBitmap("bitmap"));
assertNotNull(CACHE_DOUBLE_UTILS.getDrawable("drawable"));
assertNotNull(CACHE_DOUBLE_UTILS.getParcelable("parcelable", ParcelableTest.CREATOR));
assertNotNull(CACHE_DOUBLE_UTILS.getSerializable("serializable"));
CACHE_DOUBLE_UTILS.clear();
assertNull(CACHE_DOUBLE_UTILS.getBytes("bytes"));
assertNull(CACHE_DOUBLE_UTILS.getString("string"));
assertNull(CACHE_DOUBLE_UTILS.getJSONObject("jsonObject"));
assertNull(CACHE_DOUBLE_UTILS.getJSONArray("jsonArray"));
assertNull(CACHE_DOUBLE_UTILS.getBitmap("bitmap"));
assertNull(CACHE_DOUBLE_UTILS.getDrawable("drawable"));
assertNull(CACHE_DOUBLE_UTILS.getParcelable("parcelable", ParcelableTest.CREATOR));
assertNull(CACHE_DOUBLE_UTILS.getSerializable("serializable"));
assertEquals(0, CACHE_DOUBLE_UTILS.getCacheDiskSize());
assertEquals(0, CACHE_DOUBLE_UTILS.getCacheDiskCount());
assertEquals(0, CACHE_DOUBLE_UTILS.getCacheMemoryCount());
}
@After
public void tearDown() {
CACHE_DOUBLE_UTILS.clear();
}
static class ParcelableTest implements Parcelable {
String author;
String className;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
ParcelableTest(String author, String className) {
this.author = author;
this.className = className;
}
ParcelableTest(Parcel in) {
author = in.readString();
className = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(author);
dest.writeString(className);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<ParcelableTest> CREATOR = new Creator<ParcelableTest>() {
@Override
public ParcelableTest createFromParcel(Parcel in) {
return new ParcelableTest(in);
}
@Override
public ParcelableTest[] newArray(int size) {
return new ParcelableTest[size];
}
};
@Override
public boolean equals(Object obj) {
return obj instanceof ParcelableTest
&& ((ParcelableTest) obj).author.equals(author)
&& ((ParcelableTest) obj).className.equals(className);
}
}
static class SerializableTest implements Serializable {
private static final long serialVersionUID = -5806706668736895024L;
String author;
String className;
SerializableTest(String author, String className) {
this.author = author;
this.className = className;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
@Override
public boolean equals(Object obj) {
return obj instanceof SerializableTest
&& ((SerializableTest) obj).author.equals(author)
&& ((SerializableTest) obj).className.equals(className);
}
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/TimeUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/TimeUtilsTest.java | package com.blankj.utilcode.util;
import com.blankj.utilcode.constant.TimeConstants;
import org.junit.Test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/08/12
* desc : test TimeUtils
* </pre>
*/
public class TimeUtilsTest extends BaseTest {
private final DateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
private final DateFormat mFormat = new SimpleDateFormat("yyyy MM dd HH:mm:ss", Locale.getDefault());
private final long timeMillis = 1493887049000L;// 2017-05-04 16:37:29
private final Date timeDate = new Date(timeMillis);
private final String timeString = defaultFormat.format(timeDate);
private final String timeStringFormat = mFormat.format(timeDate);
private final long tomorrowTimeMillis = 1493973449000L;
private final Date tomorrowTimeDate = new Date(tomorrowTimeMillis);
private final String tomorrowTimeString = defaultFormat.format(tomorrowTimeDate);
private final String tomorrowTimeStringFormat = mFormat.format(tomorrowTimeDate);
private final long delta = 20;// 允许误差 10ms
@Test
public void millis2String() {
assertEquals(timeString, TimeUtils.millis2String(timeMillis));
assertEquals(timeStringFormat, TimeUtils.millis2String(timeMillis, mFormat));
assertEquals(timeStringFormat, TimeUtils.millis2String(timeMillis, "yyyy MM dd HH:mm:ss"));
}
@Test
public void string2Millis() {
assertEquals(timeMillis, TimeUtils.string2Millis(timeString));
assertEquals(timeMillis, TimeUtils.string2Millis(timeStringFormat, mFormat));
assertEquals(timeMillis, TimeUtils.string2Millis(timeStringFormat, "yyyy MM dd HH:mm:ss"));
}
@Test
public void string2Date() {
assertEquals(timeDate, TimeUtils.string2Date(timeString));
assertEquals(timeDate, TimeUtils.string2Date(timeStringFormat, mFormat));
assertEquals(timeDate, TimeUtils.string2Date(timeStringFormat, "yyyy MM dd HH:mm:ss"));
}
@Test
public void date2String() {
assertEquals(timeString, TimeUtils.date2String(timeDate));
assertEquals(timeStringFormat, TimeUtils.date2String(timeDate, mFormat));
assertEquals(timeStringFormat, TimeUtils.date2String(timeDate, "yyyy MM dd HH:mm:ss"));
}
@Test
public void date2Millis() {
assertEquals(timeMillis, TimeUtils.date2Millis(timeDate));
}
@Test
public void millis2Date() {
assertEquals(timeDate, TimeUtils.millis2Date(timeMillis));
}
@Test
public void getTimeSpan() {
long testTimeMillis = timeMillis + 120 * TimeConstants.SEC;
String testTimeString = TimeUtils.millis2String(testTimeMillis);
String testTimeStringFormat = TimeUtils.millis2String(testTimeMillis, mFormat);
Date testTimeDate = TimeUtils.millis2Date(testTimeMillis);
assertEquals(-120, TimeUtils.getTimeSpan(timeString, testTimeString, TimeConstants.SEC));
assertEquals(2, TimeUtils.getTimeSpan(testTimeStringFormat, timeStringFormat, mFormat, TimeConstants.MIN));
assertEquals(-2, TimeUtils.getTimeSpan(timeDate, testTimeDate, TimeConstants.MIN));
assertEquals(120, TimeUtils.getTimeSpan(testTimeMillis, timeMillis, TimeConstants.SEC));
}
@Test
public void getFitTimeSpan() {
long testTimeMillis = timeMillis + 10 * TimeConstants.DAY + 10 * TimeConstants.MIN + 10 * TimeConstants.SEC;
String testTimeString = TimeUtils.millis2String(testTimeMillis);
String testTimeStringFormat = TimeUtils.millis2String(testTimeMillis, mFormat);
Date testTimeDate = TimeUtils.millis2Date(testTimeMillis);
assertEquals("-10天10分钟10秒", TimeUtils.getFitTimeSpan(timeString, testTimeString, 5));
assertEquals("10天10分钟10秒", TimeUtils.getFitTimeSpan(testTimeStringFormat, timeStringFormat, mFormat, 5));
assertEquals("-10天10分钟10秒", TimeUtils.getFitTimeSpan(timeDate, testTimeDate, 5));
assertEquals("10天10分钟10秒", TimeUtils.getFitTimeSpan(testTimeMillis, timeMillis, 5));
}
@Test
public void getNowMills() {
assertEquals(System.currentTimeMillis(), TimeUtils.getNowMills(), delta);
}
@Test
public void getNowString() {
assertEquals(System.currentTimeMillis(), TimeUtils.string2Millis(TimeUtils.getNowString()), delta);
assertEquals(System.currentTimeMillis(), TimeUtils.string2Millis(TimeUtils.getNowString(mFormat), mFormat), delta);
}
@Test
public void getNowDate() {
assertEquals(System.currentTimeMillis(), TimeUtils.date2Millis(TimeUtils.getNowDate()), delta);
}
@Test
public void getTimeSpanByNow() {
assertEquals(0, TimeUtils.getTimeSpanByNow(TimeUtils.getNowString(), TimeConstants.MSEC), delta);
assertEquals(0, TimeUtils.getTimeSpanByNow(TimeUtils.getNowString(mFormat), mFormat, TimeConstants.MSEC), delta);
assertEquals(0, TimeUtils.getTimeSpanByNow(TimeUtils.getNowDate(), TimeConstants.MSEC), delta);
assertEquals(0, TimeUtils.getTimeSpanByNow(TimeUtils.getNowMills(), TimeConstants.MSEC), delta);
}
@Test
public void getFitTimeSpanByNow() {
// long spanMillis = 6 * TimeConstants.DAY + 6 * TimeConstants.HOUR + 6 * TimeConstants.MIN + 6 * TimeConstants.SEC;
// assertEquals("6天6小时6分钟6秒", TimeUtils.getFitTimeSpanByNow(TimeUtils.millis2String(System.currentTimeMillis() + spanMillis), 4));
// assertEquals("6天6小时6分钟6秒", TimeUtils.getFitTimeSpanByNow(TimeUtils.millis2String(System.currentTimeMillis() + spanMillis, mFormat), mFormat, 4));
// assertEquals("6天6小时6分钟6秒", TimeUtils.getFitTimeSpanByNow(TimeUtils.millis2Date(System.currentTimeMillis() + spanMillis), 4));
// assertEquals("6天6小时6分钟6秒", TimeUtils.getFitTimeSpanByNow(System.currentTimeMillis() + spanMillis, 4));
}
@Test
public void getFriendlyTimeSpanByNow() {
assertEquals("刚刚", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowString()));
assertEquals("刚刚", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowString(mFormat), mFormat));
assertEquals("刚刚", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowDate()));
assertEquals("刚刚", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowMills()));
assertEquals("1秒前", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowMills() - TimeConstants.SEC));
assertEquals("1分钟前", TimeUtils.getFriendlyTimeSpanByNow(TimeUtils.getNowMills() - TimeConstants.MIN));
}
@Test
public void getMillis() {
assertEquals(tomorrowTimeMillis, TimeUtils.getMillis(timeMillis, 1, TimeConstants.DAY));
assertEquals(tomorrowTimeMillis, TimeUtils.getMillis(timeString, 1, TimeConstants.DAY));
assertEquals(tomorrowTimeMillis, TimeUtils.getMillis(timeStringFormat, mFormat, 1, TimeConstants.DAY));
assertEquals(tomorrowTimeMillis, TimeUtils.getMillis(timeDate, 1, TimeConstants.DAY));
}
@Test
public void getString() {
assertEquals(tomorrowTimeString, TimeUtils.getString(timeMillis, 1, TimeConstants.DAY));
assertEquals(tomorrowTimeStringFormat, TimeUtils.getString(timeMillis, mFormat, 1, TimeConstants.DAY));
assertEquals(tomorrowTimeString, TimeUtils.getString(timeString, 1, TimeConstants.DAY));
assertEquals(tomorrowTimeStringFormat, TimeUtils.getString(timeStringFormat, mFormat, 1, TimeConstants.DAY));
assertEquals(tomorrowTimeString, TimeUtils.getString(timeDate, 1, TimeConstants.DAY));
assertEquals(tomorrowTimeStringFormat, TimeUtils.getString(timeDate, mFormat, 1, TimeConstants.DAY));
}
@Test
public void getDate() {
assertEquals(tomorrowTimeDate, TimeUtils.getDate(timeMillis, 1, TimeConstants.DAY));
assertEquals(tomorrowTimeDate, TimeUtils.getDate(timeString, 1, TimeConstants.DAY));
assertEquals(tomorrowTimeDate, TimeUtils.getDate(timeStringFormat, mFormat, 1, TimeConstants.DAY));
assertEquals(tomorrowTimeDate, TimeUtils.getDate(timeDate, 1, TimeConstants.DAY));
}
@Test
public void getMillisByNow() {
assertEquals(System.currentTimeMillis() + TimeConstants.DAY, TimeUtils.getMillisByNow(1, TimeConstants.DAY), delta);
}
@Test
public void getStringByNow() {
long tomorrowMillis = TimeUtils.string2Millis(TimeUtils.getStringByNow(1, TimeConstants.DAY));
assertEquals(System.currentTimeMillis() + TimeConstants.DAY, tomorrowMillis, delta);
tomorrowMillis = TimeUtils.string2Millis(TimeUtils.getStringByNow(1, mFormat, TimeConstants.DAY), mFormat);
assertEquals(System.currentTimeMillis() + TimeConstants.DAY, tomorrowMillis, delta);
}
@Test
public void getDateByNow() {
long tomorrowMillis = TimeUtils.date2Millis(TimeUtils.getDateByNow(1, TimeConstants.DAY));
assertEquals(System.currentTimeMillis() + TimeConstants.DAY, TimeUtils.getMillisByNow(1, TimeConstants.DAY), delta);
}
@Test
public void isToday() {
long todayTimeMillis = System.currentTimeMillis();
String todayTimeString = TimeUtils.millis2String(todayTimeMillis);
String todayTimeStringFormat = TimeUtils.millis2String(todayTimeMillis, mFormat);
Date todayTimeDate = TimeUtils.millis2Date(todayTimeMillis);
long tomorrowTimeMillis = todayTimeMillis + TimeConstants.DAY;
String tomorrowTimeString = TimeUtils.millis2String(tomorrowTimeMillis);
Date tomorrowTimeDate = TimeUtils.millis2Date(tomorrowTimeMillis);
assertTrue(TimeUtils.isToday(todayTimeString));
assertTrue(TimeUtils.isToday(todayTimeStringFormat, mFormat));
assertTrue(TimeUtils.isToday(todayTimeDate));
assertTrue(TimeUtils.isToday(todayTimeMillis));
assertFalse(TimeUtils.isToday(tomorrowTimeString));
assertFalse(TimeUtils.isToday(tomorrowTimeStringFormat, mFormat));
assertFalse(TimeUtils.isToday(tomorrowTimeDate));
assertFalse(TimeUtils.isToday(tomorrowTimeMillis));
}
@Test
public void isLeapYear() {
assertFalse(TimeUtils.isLeapYear(timeString));
assertFalse(TimeUtils.isLeapYear(timeStringFormat, mFormat));
assertFalse(TimeUtils.isLeapYear(timeDate));
assertFalse(TimeUtils.isLeapYear(timeMillis));
assertTrue(TimeUtils.isLeapYear(2016));
assertFalse(TimeUtils.isLeapYear(2017));
}
@Test
public void getChineseWeek() {
assertEquals("星期四", TimeUtils.getChineseWeek(timeString));
assertEquals("星期四", TimeUtils.getChineseWeek(timeStringFormat, mFormat));
assertEquals("星期四", TimeUtils.getChineseWeek(timeDate));
assertEquals("星期四", TimeUtils.getChineseWeek(timeMillis));
}
@Test
public void getUSWeek() {
assertEquals("Thursday", TimeUtils.getUSWeek(timeString));
assertEquals("Thursday", TimeUtils.getUSWeek(timeStringFormat, mFormat));
assertEquals("Thursday", TimeUtils.getUSWeek(timeDate));
assertEquals("Thursday", TimeUtils.getUSWeek(timeMillis));
}
//@Test
//public void isAm() {
// assertFalse(TimeUtils.isAm(timeMillis));
//}
//
//@Test
//public void isPm() {
// assertTrue(TimeUtils.isPm(timeMillis));
//}
@Test
public void getWeekIndex() {
assertEquals(5, TimeUtils.getValueByCalendarField(timeString, Calendar.DAY_OF_WEEK));
assertEquals(5, TimeUtils.getValueByCalendarField(timeString, Calendar.DAY_OF_WEEK));
assertEquals(5, TimeUtils.getValueByCalendarField(timeStringFormat, mFormat, Calendar.DAY_OF_WEEK));
assertEquals(5, TimeUtils.getValueByCalendarField(timeDate, Calendar.DAY_OF_WEEK));
assertEquals(5, TimeUtils.getValueByCalendarField(timeMillis, Calendar.DAY_OF_WEEK));
}
@Test
public void getWeekOfMonth() {
assertEquals(1, TimeUtils.getValueByCalendarField(timeString, Calendar.WEEK_OF_MONTH));
assertEquals(1, TimeUtils.getValueByCalendarField(timeStringFormat, mFormat, Calendar.WEEK_OF_MONTH));
assertEquals(1, TimeUtils.getValueByCalendarField(timeDate, Calendar.WEEK_OF_MONTH));
assertEquals(1, TimeUtils.getValueByCalendarField(timeMillis, Calendar.WEEK_OF_MONTH));
}
@Test
public void getWeekOfYear() {
assertEquals(18, TimeUtils.getValueByCalendarField(timeString, Calendar.WEEK_OF_YEAR));
assertEquals(18, TimeUtils.getValueByCalendarField(timeStringFormat, mFormat, Calendar.WEEK_OF_YEAR));
assertEquals(18, TimeUtils.getValueByCalendarField(timeDate, Calendar.WEEK_OF_YEAR));
assertEquals(18, TimeUtils.getValueByCalendarField(timeMillis, Calendar.WEEK_OF_YEAR));
}
@Test
public void getChineseZodiac() {
assertEquals("鸡", TimeUtils.getChineseZodiac(timeString));
assertEquals("鸡", TimeUtils.getChineseZodiac(timeStringFormat, mFormat));
assertEquals("鸡", TimeUtils.getChineseZodiac(timeDate));
assertEquals("鸡", TimeUtils.getChineseZodiac(timeMillis));
assertEquals("鸡", TimeUtils.getChineseZodiac(2017));
}
@Test
public void getZodiac() {
assertEquals("金牛座", TimeUtils.getZodiac(timeString));
assertEquals("金牛座", TimeUtils.getZodiac(timeStringFormat, mFormat));
assertEquals("金牛座", TimeUtils.getZodiac(timeDate));
assertEquals("金牛座", TimeUtils.getZodiac(timeMillis));
assertEquals("狮子座", TimeUtils.getZodiac(8, 16));
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/TestConfig.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/TestConfig.java | package com.blankj.utilcode.util;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/09/10
* desc : config of test
* </pre>
*/
public class TestConfig {
static final String FILE_SEP = System.getProperty("file.separator");
static final String LINE_SEP = System.getProperty("line.separator");
static final String TEST_PATH;
static {
String projectPath = System.getProperty("user.dir");
if (!projectPath.contains("utilcode")) {
projectPath += FILE_SEP + "utilcode";
}
TEST_PATH = projectPath + FILE_SEP + "src" + FILE_SEP + "test" + FILE_SEP + "res" + FILE_SEP;
}
static final String PATH_TEMP = TEST_PATH + "temp" + FILE_SEP;
static final String PATH_CACHE = TEST_PATH + "cache" + FILE_SEP;
static final String PATH_ENCRYPT = TEST_PATH + "encrypt" + FILE_SEP;
static final String PATH_FILE = TEST_PATH + "file" + FILE_SEP;
static final String PATH_IMAGE = TEST_PATH + "image" + FILE_SEP;
static final String PATH_ZIP = TEST_PATH + "zip" + FILE_SEP;
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/TestHierarchicalMethodsSubclass.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/TestHierarchicalMethodsSubclass.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class TestHierarchicalMethodsSubclass extends TestHierarchicalMethodsBase {
public static String PUBLIC_RESULT = "PUBLIC_SUB";
public static String PRIVATE_RESULT = "PRIVATE_SUB";
// Both of these are hiding fields in the super type
private int invisibleField2;
public int visibleField2;
private int invisibleField3;
public int visibleField3;
private String priv_method(int number) {
return PRIVATE_RESULT;
}
private String pub_method(Integer number) {
return PRIVATE_RESULT;
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test9.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test9.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/05/03
* desc :
* </pre>
*/
public interface Test9 {
String substring(int beginIndex);
String substring(int beginIndex, int endIndex);
String substring(Integer beginIndex);
String substring(Integer beginIndex, Integer endIndex);
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/TestHierarchicalMethodsBase.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/TestHierarchicalMethodsBase.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class TestHierarchicalMethodsBase {
public static String PUBLIC_RESULT = "PUBLIC_BASE";
public static String PRIVATE_RESULT = "PRIVATE_BASE";
private int invisibleField1;
private int invisibleField2;
public int visibleField1;
public int visibleField2;
public String pub_base_method(int number) {
return PUBLIC_RESULT;
}
public String pub_method(int number) {
return PUBLIC_RESULT;
}
private String priv_method(int number) {
return PRIVATE_RESULT;
}
private String very_priv_method() {
return PRIVATE_RESULT;
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test2.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test2.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class Test2 {
public final Object n;
public final ConstructorType constructorType;
public Test2() {
this.n = null;
this.constructorType = ConstructorType.NO_ARGS;
}
public Test2(Integer n) {
this.n = n;
this.constructorType = ConstructorType.INTEGER;
}
public Test2(Number n) {
this.n = n;
this.constructorType = ConstructorType.NUMBER;
}
public Test2(Object n) {
this.n = n;
this.constructorType = ConstructorType.OBJECT;
}
public static enum ConstructorType {
NO_ARGS,
INTEGER,
NUMBER,
OBJECT
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test1.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test1.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class Test1 {
public static int S_INT1;
public static Integer S_INT2;
public int I_INT1;
public Integer I_INT2;
public static Test1 S_DATA;
public Test1 I_DATA;
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/PrivateConstructors.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/PrivateConstructors.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class PrivateConstructors {
public final String string;
private PrivateConstructors() {
this(null);
}
private PrivateConstructors(String string) {
this.string = string;
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test10.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test10.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/05/03
* desc :
* </pre>
*/
public interface Test10 {
void setFoo(String s);
void setBar(boolean b);
void setBaz(String baz);
void testIgnore();
String getFoo();
boolean isBar();
String getBaz();
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test7.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test7.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class Test7 {
public final String s;
public final Integer i;
private Test7(int i) {
this(null, i);
}
private Test7(String s) {
this(s, null);
}
private Test7(String s, int i) {
this(s, (Integer) i);
}
private Test7(String s, Integer i) {
this.s = s;
this.i = i;
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test5.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test5.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class Test5 {
private static void s_method() {
}
private void i_method() {
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test3.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test3.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class Test3 {
public Object n;
public MethodType methodType;
public void method() {
this.n = null;
this.methodType = MethodType.NO_ARGS;
}
public void method(Integer n1) {
this.n = n1;
this.methodType = MethodType.INTEGER;
}
public void method(Number n1) {
this.n = n1;
this.methodType = MethodType.NUMBER;
}
public void method(Object n1) {
this.n = n1;
this.methodType = MethodType.OBJECT;
}
public static enum MethodType {
NO_ARGS,
INTEGER,
NUMBER,
OBJECT
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test8.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test8.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class Test8 {
public static final int SF_INT1 = new Integer(0);
public static final Integer SF_INT2 = new Integer(0);
public final int F_INT1 = new Integer(0);
public final Integer F_INT2 = new Integer(0);
public static Test8 S_DATA;
public Test8 I_DATA;
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/ReflectUtilsTest.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/ReflectUtilsTest.java | package com.blankj.utilcode.util.reflect;
import com.blankj.utilcode.util.ReflectUtils;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/12/15
* desc : ReflectUtils 单元测试
* </pre>
*/
public class ReflectUtilsTest {
@Rule
public final ExpectedException expectedException = ExpectedException.none();
@Test
public void reflect() {
Assert.assertEquals(
ReflectUtils.reflect(Object.class),
ReflectUtils.reflect("java.lang.Object", ClassLoader.getSystemClassLoader())
);
assertEquals(
ReflectUtils.reflect(Object.class),
ReflectUtils.reflect("java.lang.Object")
);
assertEquals(
ReflectUtils.reflect(String.class).get(),
ReflectUtils.reflect("java.lang.String").get()
);
assertEquals(
Object.class,
ReflectUtils.reflect(Object.class).get()
);
assertEquals(
"abc",
ReflectUtils.reflect((Object) "abc").get()
);
assertEquals(
1,
ReflectUtils.reflect(1).get()
);
}
@Test
public void newInstance() {
assertEquals(
"",
ReflectUtils.reflect(String.class).newInstance().get()
);
assertEquals(
"abc",
ReflectUtils.reflect(String.class).newInstance("abc").get()
);
assertEquals(
"abc",
ReflectUtils.reflect(String.class).newInstance("abc".getBytes()).get()
);
assertEquals(
"abc",
ReflectUtils.reflect(String.class).newInstance("abc".toCharArray()).get()
);
assertEquals(
"b",
ReflectUtils.reflect(String.class).newInstance("abc".toCharArray(), 1, 1).get()
);
}
@Test
public void newInstancePrivate() {
assertNull(ReflectUtils.reflect(PrivateConstructors.class).newInstance().field("string").get());
assertEquals(
"abc",
ReflectUtils.reflect(PrivateConstructors.class).newInstance("abc").field("string").get()
);
}
@Test
public void newInstanceNull() {
Test2 test2 = ReflectUtils.reflect(Test2.class).newInstance((Object) null).get();
assertNull(test2.n);
}
@Test
public void newInstanceWithPrivate() {
Test7 t1 = ReflectUtils.reflect(Test7.class).newInstance(1).get();
assertEquals(1, (int) t1.i);
assertNull(t1.s);
Test7 t2 = ReflectUtils.reflect(Test7.class).newInstance("a").get();
assertNull(t2.i);
assertEquals("a", t2.s);
Test7 t3 = ReflectUtils.reflect(Test7.class).newInstance("a", 1).get();
assertEquals(1, (int) t3.i);
assertEquals("a", t3.s);
}
@Test
public void newInstanceAmbiguity() {
Test2 test;
test = ReflectUtils.reflect(Test2.class).newInstance().get();
assertEquals(null, test.n);
assertEquals(Test2.ConstructorType.NO_ARGS, test.constructorType);
test = ReflectUtils.reflect(Test2.class).newInstance("abc").get();
assertEquals("abc", test.n);
assertEquals(Test2.ConstructorType.OBJECT, test.constructorType);
test = ReflectUtils.reflect(Test2.class).newInstance(new Long("1")).get();
assertEquals(1L, test.n);
assertEquals(Test2.ConstructorType.NUMBER, test.constructorType);
test = ReflectUtils.reflect(Test2.class).newInstance(1).get();
assertEquals(1, test.n);
assertEquals(Test2.ConstructorType.INTEGER, test.constructorType);
test = ReflectUtils.reflect(Test2.class).newInstance('a').get();
assertEquals('a', test.n);
assertEquals(Test2.ConstructorType.OBJECT, test.constructorType);
}
@Test
public void method() {
// instance methods
assertEquals(
"",
ReflectUtils.reflect((Object) " ").method("trim").get()
);
assertEquals(
"12",
ReflectUtils.reflect((Object) " 12 ").method("trim").get()
);
assertEquals(
"34",
ReflectUtils.reflect((Object) "1234").method("substring", 2).get()
);
assertEquals(
"12",
ReflectUtils.reflect((Object) "1234").method("substring", 0, 2).get()
);
assertEquals(
"1234",
ReflectUtils.reflect((Object) "12").method("concat", "34").get()
);
assertEquals(
"123456",
ReflectUtils.reflect((Object) "12").method("concat", "34").method("concat", "56").get()
);
assertEquals(
2,
ReflectUtils.reflect((Object) "1234").method("indexOf", "3").get()
);
assertEquals(
2.0f,
(float) ReflectUtils.reflect((Object) "1234").method("indexOf", "3").method("floatValue").get(),
0.0f
);
assertEquals(
"2",
ReflectUtils.reflect((Object) "1234").method("indexOf", "3").method("toString").get()
);
// static methods
assertEquals(
"true",
ReflectUtils.reflect(String.class).method("valueOf", true).get()
);
assertEquals(
"1",
ReflectUtils.reflect(String.class).method("valueOf", 1).get()
);
assertEquals(
"abc",
ReflectUtils.reflect(String.class).method("valueOf", "abc".toCharArray()).get()
);
assertEquals(
"abc",
ReflectUtils.reflect(String.class).method("copyValueOf", "abc".toCharArray()).get()
);
assertEquals(
"b",
ReflectUtils.reflect(String.class).method("copyValueOf", "abc".toCharArray(), 1, 1).get()
);
}
@Test
public void methodVoid() {
// instance methods
Test4 test4 = new Test4();
assertEquals(
test4,
ReflectUtils.reflect(test4).method("i_method").get()
);
// static methods
assertEquals(
Test4.class,
ReflectUtils.reflect(Test4.class).method("s_method").get()
);
}
@Test
public void methodPrivate() {
// instance methods
Test5 test8 = new Test5();
assertEquals(
test8,
ReflectUtils.reflect(test8).method("i_method").get()
);
// static methods
assertEquals(
Test5.class,
ReflectUtils.reflect(Test5.class).method("s_method").get()
);
}
@Test
public void methodNullArguments() {
Test6 test9 = new Test6();
ReflectUtils.reflect(test9).method("put", "key", "value");
assertTrue(test9.map.containsKey("key"));
assertEquals("value", test9.map.get("key"));
ReflectUtils.reflect(test9).method("put", "key", null);
assertTrue(test9.map.containsKey("key"));
assertNull(test9.map.get("key"));
}
@Test
public void methodSuper() {
TestHierarchicalMethodsSubclass subclass = new TestHierarchicalMethodsSubclass();
assertEquals(
TestHierarchicalMethodsBase.PUBLIC_RESULT,
ReflectUtils.reflect(subclass).method("pub_base_method", 1).get()
);
assertEquals(
TestHierarchicalMethodsBase.PRIVATE_RESULT,
ReflectUtils.reflect(subclass).method("very_priv_method").get()
);
}
@Test
public void methodDeclaring() {
TestHierarchicalMethodsSubclass subclass = new TestHierarchicalMethodsSubclass();
assertEquals(
TestHierarchicalMethodsSubclass.PRIVATE_RESULT,
ReflectUtils.reflect(subclass).method("priv_method", 1).get()
);
TestHierarchicalMethodsBase baseClass = new TestHierarchicalMethodsBase();
assertEquals(
TestHierarchicalMethodsBase.PRIVATE_RESULT,
ReflectUtils.reflect(baseClass).method("priv_method", 1).get()
);
}
@Test
public void methodAmbiguity() {
Test3 test;
test = ReflectUtils.reflect(Test3.class).newInstance().method("method").get();
assertEquals(null, test.n);
assertEquals(Test3.MethodType.NO_ARGS, test.methodType);
test = ReflectUtils.reflect(Test3.class).newInstance().method("method", "abc").get();
assertEquals("abc", test.n);
assertEquals(Test3.MethodType.OBJECT, test.methodType);
test = ReflectUtils.reflect(Test3.class).newInstance().method("method", new Long("1")).get();
assertEquals(1L, test.n);
assertEquals(Test3.MethodType.NUMBER, test.methodType);
test = ReflectUtils.reflect(Test3.class).newInstance().method("method", 1).get();
assertEquals(1, test.n);
assertEquals(Test3.MethodType.INTEGER, test.methodType);
test = ReflectUtils.reflect(Test3.class).newInstance().method("method", 'a').get();
assertEquals('a', test.n);
assertEquals(Test3.MethodType.OBJECT, test.methodType);
}
@Test
public void field() {
// instance field
Test1 test1 = new Test1();
ReflectUtils.reflect(test1).field("I_INT1", 1);
assertEquals(1, ReflectUtils.reflect(test1).field("I_INT1").get());
ReflectUtils.reflect(test1).field("I_INT2", 1);
assertEquals(1, ReflectUtils.reflect(test1).field("I_INT2").get());
ReflectUtils.reflect(test1).field("I_INT2", null);
assertNull(ReflectUtils.reflect(test1).field("I_INT2").get());
// static field
ReflectUtils.reflect(Test1.class).field("S_INT1", 1);
assertEquals(1, ReflectUtils.reflect(Test1.class).field("S_INT1").get());
ReflectUtils.reflect(Test1.class).field("S_INT2", 1);
assertEquals(1, ReflectUtils.reflect(Test1.class).field("S_INT2").get());
ReflectUtils.reflect(Test1.class).field("S_INT2", null);
assertNull(ReflectUtils.reflect(Test1.class).field("S_INT2").get());
// hierarchies field
TestHierarchicalMethodsSubclass test2 = new TestHierarchicalMethodsSubclass();
ReflectUtils.reflect(test2).field("invisibleField1", 1);
assertEquals(1, ReflectUtils.reflect(test2).field("invisibleField1").get());
ReflectUtils.reflect(test2).field("invisibleField2", 1);
assertEquals(1, ReflectUtils.reflect(test2).field("invisibleField2").get());
ReflectUtils.reflect(test2).field("invisibleField3", 1);
assertEquals(1, ReflectUtils.reflect(test2).field("invisibleField3").get());
ReflectUtils.reflect(test2).field("visibleField1", 1);
assertEquals(1, ReflectUtils.reflect(test2).field("visibleField1").get());
ReflectUtils.reflect(test2).field("visibleField2", 1);
assertEquals(1, ReflectUtils.reflect(test2).field("visibleField2").get());
ReflectUtils.reflect(test2).field("visibleField3", 1);
assertEquals(1, ReflectUtils.reflect(test2).field("visibleField3").get());
}
@Test
public void fieldPrivate() {
class Foo {
private String bar;
}
Foo foo = new Foo();
ReflectUtils.reflect(foo).field("bar", "FooBar");
assertThat(foo.bar, Matchers.is("FooBar"));
assertEquals("FooBar", ReflectUtils.reflect(foo).field("bar").get());
ReflectUtils.reflect(foo).field("bar", null);
assertNull(foo.bar);
assertNull(ReflectUtils.reflect(foo).field("bar").get());
}
@Test
public void fieldFinal() {
// instance field
Test8 test11 = new Test8();
ReflectUtils.reflect(test11).field("F_INT1", 1);
assertEquals(1, ReflectUtils.reflect(test11).field("F_INT1").get());
ReflectUtils.reflect(test11).field("F_INT2", 1);
assertEquals(1, ReflectUtils.reflect(test11).field("F_INT2").get());
ReflectUtils.reflect(test11).field("F_INT2", null);
assertNull(ReflectUtils.reflect(test11).field("F_INT2").get());
// static field
ReflectUtils.reflect(Test8.class).field("SF_INT1", 1);
assertEquals(1, ReflectUtils.reflect(Test8.class).field("SF_INT1").get());
ReflectUtils.reflect(Test8.class).field("SF_INT2", 1);
assertEquals(1, ReflectUtils.reflect(Test8.class).field("SF_INT2").get());
ReflectUtils.reflect(Test8.class).field("SF_INT2", null);
assertNull(ReflectUtils.reflect(Test8.class).field("SF_INT2").get());
}
@Test
public void fieldPrivateStaticFinal() {
assertEquals(1, ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I1").get());
assertEquals(1, ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I2").get());
ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I1", 2);
ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I2", 2);
assertEquals(2, ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I1").get());
assertEquals(2, ReflectUtils.reflect(TestPrivateStaticFinal.class).field("I2").get());
}
@Test
public void fieldAdvanced() {
ReflectUtils.reflect(Test1.class)
.field("S_DATA", ReflectUtils.reflect(Test1.class).newInstance())
.field("S_DATA")
.field("I_DATA", ReflectUtils.reflect(Test1.class).newInstance())
.field("I_DATA")
.field("I_INT1", 1)
.field("S_INT1", 2);
assertEquals(2, Test1.S_INT1);
assertEquals(null, Test1.S_INT2);
assertEquals(0, Test1.S_DATA.I_INT1);
assertEquals(null, Test1.S_DATA.I_INT2);
assertEquals(1, Test1.S_DATA.I_DATA.I_INT1);
assertEquals(null, Test1.S_DATA.I_DATA.I_INT2);
}
@Test
public void fieldFinalAdvanced() {
ReflectUtils.reflect(Test8.class)
.field("S_DATA", ReflectUtils.reflect(Test8.class).newInstance())
.field("S_DATA")
.field("I_DATA", ReflectUtils.reflect(Test8.class).newInstance())
.field("I_DATA")
.field("F_INT1", 1)
.field("F_INT2", 1)
.field("SF_INT1", 2)
.field("SF_INT2", 2);
assertEquals(2, Test8.SF_INT1);
assertEquals(new Integer(2), Test8.SF_INT2);
assertEquals(0, Test8.S_DATA.F_INT1);
assertEquals(new Integer(0), Test8.S_DATA.F_INT2);
assertEquals(1, Test8.S_DATA.I_DATA.F_INT1);
assertEquals(new Integer(1), Test8.S_DATA.I_DATA.F_INT2);
}
@Test
public void _hashCode() {
Object object = new Object();
assertEquals(ReflectUtils.reflect(object).hashCode(), object.hashCode());
}
@Test
public void _toString() {
Object object = new Object() {
@Override
public String toString() {
return "test";
}
};
assertEquals(ReflectUtils.reflect(object).toString(), object.toString());
}
@Test
public void _equals() {
Object object = new Object();
ReflectUtils a = ReflectUtils.reflect(object);
ReflectUtils b = ReflectUtils.reflect(object);
ReflectUtils c = ReflectUtils.reflect(object);
assertTrue(b.equals(a));
assertTrue(a.equals(b));
assertTrue(b.equals(c));
assertTrue(a.equals(c));
//noinspection ObjectEqualsNull
assertFalse(a.equals(null));
}
@Test
public void testProxy() {
assertEquals("abc", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(0));
assertEquals("bc", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(1));
assertEquals("c", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(2));
assertEquals("a", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(0, 1));
assertEquals("b", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(1, 2));
assertEquals("c", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(2, 3));
assertEquals("abc", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(0));
assertEquals("bc", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(1));
assertEquals("c", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(2));
assertEquals("a", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(0, 1));
assertEquals("b", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(1, 2));
assertEquals("c", ReflectUtils.reflect((Object) "abc").proxy(Test9.class).substring(2, 3));
}
@Test
public void testMapProxy() {
class MyMap extends HashMap<String, Object> {
private String baz;
public void setBaz(String baz) {
this.baz = "MyMap: " + baz;
}
public String getBaz() {
return baz;
}
}
Map<String, Object> map = new MyMap();
ReflectUtils.reflect(map).proxy(Test10.class).setFoo("abc");
assertEquals(1, map.size());
assertEquals("abc", map.get("foo"));
assertEquals("abc", ReflectUtils.reflect(map).proxy(Test10.class).getFoo());
ReflectUtils.reflect(map).proxy(Test10.class).setBar(true);
assertEquals(2, map.size());
assertEquals(true, map.get("bar"));
assertEquals(true, ReflectUtils.reflect(map).proxy(Test10.class).isBar());
ReflectUtils.reflect(map).proxy(Test10.class).setBaz("baz");
assertEquals(2, map.size());
assertEquals(null, map.get("baz"));
assertEquals("MyMap: baz", ReflectUtils.reflect(map).proxy(Test10.class).getBaz());
try {
ReflectUtils.reflect(map).proxy(Test10.class).testIgnore();
fail();
} catch (ReflectUtils.ReflectException ignored) {
}
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/TestPrivateStaticFinal.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/TestPrivateStaticFinal.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class TestPrivateStaticFinal {
private static final int I1 = new Integer(1);
private static final Integer I2 = new Integer(1);
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test6.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test6.java | package com.blankj.utilcode.util.reflect;
import java.util.HashMap;
import java.util.Map;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class Test6 {
public Map<String, String> map = new HashMap<String, String>();
public void put(String name, String value) {
map.put(name, value);
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test4.java | lib/utilcode/src/test/java/com/blankj/utilcode/util/reflect/Test4.java | package com.blankj.utilcode.util.reflect;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/01/12
* desc :
* </pre>
*/
public class Test4 {
public static void s_method() {
}
public void i_method() {
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/CacheDoubleStaticUtils.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/CacheDoubleStaticUtils.java | package com.blankj.utilcode.util;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Parcelable;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.Serializable;
import androidx.annotation.NonNull;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/01/04
* desc : utils about double cache
* </pre>
*/
public final class CacheDoubleStaticUtils {
private static CacheDoubleUtils sDefaultCacheDoubleUtils;
/**
* Set the default instance of {@link CacheDoubleUtils}.
*
* @param cacheDoubleUtils The default instance of {@link CacheDoubleUtils}.
*/
public static void setDefaultCacheDoubleUtils(final CacheDoubleUtils cacheDoubleUtils) {
sDefaultCacheDoubleUtils = cacheDoubleUtils;
}
/**
* Put bytes in cache.
*
* @param key The key of cache.
* @param value The value of cache.
*/
public static void put(@NonNull final String key, final byte[] value) {
put(key, value, getDefaultCacheDoubleUtils());
}
/**
* Put bytes in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
*/
public static void put(@NonNull final String key, byte[] value, final int saveTime) {
put(key, value, saveTime, getDefaultCacheDoubleUtils());
}
/**
* Return the bytes in cache.
*
* @param key The key of cache.
* @return the bytes if cache exists or null otherwise
*/
public static byte[] getBytes(@NonNull final String key) {
return getBytes(key, getDefaultCacheDoubleUtils());
}
/**
* Return the bytes in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @return the bytes if cache exists or defaultValue otherwise
*/
public static byte[] getBytes(@NonNull final String key, final byte[] defaultValue) {
return getBytes(key, defaultValue, getDefaultCacheDoubleUtils());
}
///////////////////////////////////////////////////////////////////////////
// about String
///////////////////////////////////////////////////////////////////////////
/**
* Put string value in cache.
*
* @param key The key of cache.
* @param value The value of cache.
*/
public static void put(@NonNull final String key, final String value) {
put(key, value, getDefaultCacheDoubleUtils());
}
/**
* Put string value in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
*/
public static void put(@NonNull final String key, final String value, final int saveTime) {
put(key, value, saveTime, getDefaultCacheDoubleUtils());
}
/**
* Return the string value in cache.
*
* @param key The key of cache.
* @return the string value if cache exists or null otherwise
*/
public static String getString(@NonNull final String key) {
return getString(key, getDefaultCacheDoubleUtils());
}
/**
* Return the string value in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @return the string value if cache exists or defaultValue otherwise
*/
public static String getString(@NonNull final String key, final String defaultValue) {
return getString(key, defaultValue, getDefaultCacheDoubleUtils());
}
///////////////////////////////////////////////////////////////////////////
// about JSONObject
///////////////////////////////////////////////////////////////////////////
/**
* Put JSONObject in cache.
*
* @param key The key of cache.
* @param value The value of cache.
*/
public static void put(@NonNull final String key, final JSONObject value) {
put(key, value, getDefaultCacheDoubleUtils());
}
/**
* Put JSONObject in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
*/
public static void put(@NonNull final String key,
final JSONObject value,
final int saveTime) {
put(key, value, saveTime, getDefaultCacheDoubleUtils());
}
/**
* Return the JSONObject in cache.
*
* @param key The key of cache.
* @return the JSONObject if cache exists or null otherwise
*/
public static JSONObject getJSONObject(@NonNull final String key) {
return getJSONObject(key, getDefaultCacheDoubleUtils());
}
/**
* Return the JSONObject in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @return the JSONObject if cache exists or defaultValue otherwise
*/
public static JSONObject getJSONObject(@NonNull final String key, final JSONObject defaultValue) {
return getJSONObject(key, defaultValue, getDefaultCacheDoubleUtils());
}
///////////////////////////////////////////////////////////////////////////
// about JSONArray
///////////////////////////////////////////////////////////////////////////
/**
* Put JSONArray in cache.
*
* @param key The key of cache.
* @param value The value of cache.
*/
public static void put(@NonNull final String key, final JSONArray value) {
put(key, value, getDefaultCacheDoubleUtils());
}
/**
* Put JSONArray in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
*/
public static void put(@NonNull final String key, final JSONArray value, final int saveTime) {
put(key, value, saveTime, getDefaultCacheDoubleUtils());
}
/**
* Return the JSONArray in cache.
*
* @param key The key of cache.
* @return the JSONArray if cache exists or null otherwise
*/
public static JSONArray getJSONArray(@NonNull final String key) {
return getJSONArray(key, getDefaultCacheDoubleUtils());
}
/**
* Return the JSONArray in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @return the JSONArray if cache exists or defaultValue otherwise
*/
public static JSONArray getJSONArray(@NonNull final String key, final JSONArray defaultValue) {
return getJSONArray(key, defaultValue, getDefaultCacheDoubleUtils());
}
///////////////////////////////////////////////////////////////////////////
// Bitmap cache
///////////////////////////////////////////////////////////////////////////
/**
* Put bitmap in cache.
*
* @param key The key of cache.
* @param value The value of cache.
*/
public static void put(@NonNull final String key, final Bitmap value) {
put(key, value, getDefaultCacheDoubleUtils());
}
/**
* Put bitmap in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
*/
public static void put(@NonNull final String key, final Bitmap value, final int saveTime) {
put(key, value, saveTime, getDefaultCacheDoubleUtils());
}
/**
* Return the bitmap in cache.
*
* @param key The key of cache.
* @return the bitmap if cache exists or null otherwise
*/
public static Bitmap getBitmap(@NonNull final String key) {
return getBitmap(key, getDefaultCacheDoubleUtils());
}
/**
* Return the bitmap in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @return the bitmap if cache exists or defaultValue otherwise
*/
public static Bitmap getBitmap(@NonNull final String key, final Bitmap defaultValue) {
return getBitmap(key, defaultValue, getDefaultCacheDoubleUtils());
}
///////////////////////////////////////////////////////////////////////////
// about Drawable
///////////////////////////////////////////////////////////////////////////
/**
* Put drawable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
*/
public static void put(@NonNull final String key, final Drawable value) {
put(key, value, getDefaultCacheDoubleUtils());
}
/**
* Put drawable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
*/
public static void put(@NonNull final String key, final Drawable value, final int saveTime) {
put(key, value, saveTime, getDefaultCacheDoubleUtils());
}
/**
* Return the drawable in cache.
*
* @param key The key of cache.
* @return the drawable if cache exists or null otherwise
*/
public static Drawable getDrawable(@NonNull final String key) {
return getDrawable(key, getDefaultCacheDoubleUtils());
}
/**
* Return the drawable in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @return the drawable if cache exists or defaultValue otherwise
*/
public static Drawable getDrawable(@NonNull final String key, final Drawable defaultValue) {
return getDrawable(key, defaultValue, getDefaultCacheDoubleUtils());
}
///////////////////////////////////////////////////////////////////////////
// about Parcelable
///////////////////////////////////////////////////////////////////////////
/**
* Put parcelable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
*/
public static void put(@NonNull final String key, final Parcelable value) {
put(key, value, getDefaultCacheDoubleUtils());
}
/**
* Put parcelable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
*/
public static void put(@NonNull final String key, final Parcelable value, final int saveTime) {
put(key, value, saveTime, getDefaultCacheDoubleUtils());
}
/**
* Return the parcelable in cache.
*
* @param key The key of cache.
* @param creator The creator.
* @param <T> The value type.
* @return the parcelable if cache exists or null otherwise
*/
public static <T> T getParcelable(@NonNull final String key,
@NonNull final Parcelable.Creator<T> creator) {
return getParcelable(key, creator, getDefaultCacheDoubleUtils());
}
/**
* Return the parcelable in cache.
*
* @param key The key of cache.
* @param creator The creator.
* @param defaultValue The default value if the cache doesn't exist.
* @param <T> The value type.
* @return the parcelable if cache exists or defaultValue otherwise
*/
public static <T> T getParcelable(@NonNull final String key,
@NonNull final Parcelable.Creator<T> creator,
final T defaultValue) {
return getParcelable(key, creator, defaultValue, getDefaultCacheDoubleUtils());
}
///////////////////////////////////////////////////////////////////////////
// about Serializable
///////////////////////////////////////////////////////////////////////////
/**
* Put serializable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
*/
public static void put(@NonNull final String key, final Serializable value) {
put(key, value, getDefaultCacheDoubleUtils());
}
/**
* Put serializable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
*/
public static void put(@NonNull final String key, final Serializable value, final int saveTime) {
put(key, value, saveTime, getDefaultCacheDoubleUtils());
}
/**
* Return the serializable in cache.
*
* @param key The key of cache.
* @return the bitmap if cache exists or null otherwise
*/
public static Object getSerializable(@NonNull final String key) {
return getSerializable(key, getDefaultCacheDoubleUtils());
}
/**
* Return the serializable in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @return the bitmap if cache exists or defaultValue otherwise
*/
public static Object getSerializable(@NonNull final String key, final Object defaultValue) {
return getSerializable(key, defaultValue, getDefaultCacheDoubleUtils());
}
/**
* Return the size of cache in disk.
*
* @return the size of cache in disk
*/
public static long getCacheDiskSize() {
return getCacheDiskSize(getDefaultCacheDoubleUtils());
}
/**
* Return the count of cache in disk.
*
* @return the count of cache in disk
*/
public static int getCacheDiskCount() {
return getCacheDiskCount(getDefaultCacheDoubleUtils());
}
/**
* Return the count of cache in memory.
*
* @return the count of cache in memory.
*/
public static int getCacheMemoryCount() {
return getCacheMemoryCount(getDefaultCacheDoubleUtils());
}
/**
* Remove the cache by key.
*
* @param key The key of cache.
*/
public static void remove(@NonNull String key) {
remove(key, getDefaultCacheDoubleUtils());
}
/**
* Clear all of the cache.
*/
public static void clear() {
clear(getDefaultCacheDoubleUtils());
}
///////////////////////////////////////////////////////////////////////////
// dividing line
///////////////////////////////////////////////////////////////////////////
/**
* Put bytes in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final byte[] value,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value);
}
/**
* Put bytes in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final byte[] value,
final int saveTime,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value, saveTime);
}
/**
* Return the bytes in cache.
*
* @param key The key of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the bytes if cache exists or null otherwise
*/
public static byte[] getBytes(@NonNull final String key, @NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getBytes(key);
}
/**
* Return the bytes in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the bytes if cache exists or defaultValue otherwise
*/
public static byte[] getBytes(@NonNull final String key,
final byte[] defaultValue,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getBytes(key, defaultValue);
}
///////////////////////////////////////////////////////////////////////////
// about String
///////////////////////////////////////////////////////////////////////////
/**
* Put string value in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final String value,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value);
}
/**
* Put string value in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final String value,
final int saveTime,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value, saveTime);
}
/**
* Return the string value in cache.
*
* @param key The key of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the string value if cache exists or null otherwise
*/
public static String getString(@NonNull final String key, @NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getString(key);
}
/**
* Return the string value in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the string value if cache exists or defaultValue otherwise
*/
public static String getString(@NonNull final String key,
final String defaultValue,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getString(key, defaultValue);
}
///////////////////////////////////////////////////////////////////////////
// about JSONObject
///////////////////////////////////////////////////////////////////////////
/**
* Put JSONObject in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final JSONObject value,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value);
}
/**
* Put JSONObject in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final JSONObject value,
final int saveTime,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value, saveTime);
}
/**
* Return the JSONObject in cache.
*
* @param key The key of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the JSONObject if cache exists or null otherwise
*/
public static JSONObject getJSONObject(@NonNull final String key,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getJSONObject(key);
}
/**
* Return the JSONObject in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the JSONObject if cache exists or defaultValue otherwise
*/
public static JSONObject getJSONObject(@NonNull final String key,
final JSONObject defaultValue,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getJSONObject(key, defaultValue);
}
///////////////////////////////////////////////////////////////////////////
// about JSONArray
///////////////////////////////////////////////////////////////////////////
/**
* Put JSONArray in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final JSONArray value,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value);
}
/**
* Put JSONArray in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final JSONArray value,
final int saveTime,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value, saveTime);
}
/**
* Return the JSONArray in cache.
*
* @param key The key of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the JSONArray if cache exists or null otherwise
*/
public static JSONArray getJSONArray(@NonNull final String key, @NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getJSONArray(key);
}
/**
* Return the JSONArray in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the JSONArray if cache exists or defaultValue otherwise
*/
public static JSONArray getJSONArray(@NonNull final String key,
final JSONArray defaultValue,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getJSONArray(key, defaultValue);
}
///////////////////////////////////////////////////////////////////////////
// Bitmap cache
///////////////////////////////////////////////////////////////////////////
/**
* Put bitmap in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final Bitmap value,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value);
}
/**
* Put bitmap in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final Bitmap value,
final int saveTime,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value, saveTime);
}
/**
* Return the bitmap in cache.
*
* @param key The key of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the bitmap if cache exists or null otherwise
*/
public static Bitmap getBitmap(@NonNull final String key, @NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getBitmap(key);
}
/**
* Return the bitmap in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the bitmap if cache exists or defaultValue otherwise
*/
public static Bitmap getBitmap(@NonNull final String key,
final Bitmap defaultValue,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getBitmap(key, defaultValue);
}
///////////////////////////////////////////////////////////////////////////
// about Drawable
///////////////////////////////////////////////////////////////////////////
/**
* Put drawable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final Drawable value,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value);
}
/**
* Put drawable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final Drawable value,
final int saveTime,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value, saveTime);
}
/**
* Return the drawable in cache.
*
* @param key The key of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the drawable if cache exists or null otherwise
*/
public static Drawable getDrawable(@NonNull final String key, @NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getDrawable(key);
}
/**
* Return the drawable in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the drawable if cache exists or defaultValue otherwise
*/
public static Drawable getDrawable(@NonNull final String key,
final Drawable defaultValue,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getDrawable(key, defaultValue);
}
///////////////////////////////////////////////////////////////////////////
// about Parcelable
///////////////////////////////////////////////////////////////////////////
/**
* Put parcelable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final Parcelable value,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value);
}
/**
* Put parcelable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final Parcelable value,
final int saveTime,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value, saveTime);
}
/**
* Return the parcelable in cache.
*
* @param key The key of cache.
* @param creator The creator.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @param <T> The value type.
* @return the parcelable if cache exists or null otherwise
*/
public static <T> T getParcelable(@NonNull final String key,
@NonNull final Parcelable.Creator<T> creator,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getParcelable(key, creator);
}
/**
* Return the parcelable in cache.
*
* @param key The key of cache.
* @param creator The creator.
* @param defaultValue The default value if the cache doesn't exist.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @param <T> The value type.
* @return the parcelable if cache exists or defaultValue otherwise
*/
public static <T> T getParcelable(@NonNull final String key,
@NonNull final Parcelable.Creator<T> creator,
final T defaultValue,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getParcelable(key, creator, defaultValue);
}
///////////////////////////////////////////////////////////////////////////
// about Serializable
///////////////////////////////////////////////////////////////////////////
/**
* Put serializable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final Serializable value,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value);
}
/**
* Put serializable in cache.
*
* @param key The key of cache.
* @param value The value of cache.
* @param saveTime The save time of cache, in seconds.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
*/
public static void put(@NonNull final String key,
final Serializable value,
final int saveTime,
@NonNull final CacheDoubleUtils cacheDoubleUtils) {
cacheDoubleUtils.put(key, value, saveTime);
}
/**
* Return the serializable in cache.
*
* @param key The key of cache.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the bitmap if cache exists or null otherwise
*/
public static Object getSerializable(@NonNull final String key, @NonNull final CacheDoubleUtils cacheDoubleUtils) {
return cacheDoubleUtils.getSerializable(key);
}
/**
* Return the serializable in cache.
*
* @param key The key of cache.
* @param defaultValue The default value if the cache doesn't exist.
* @param cacheDoubleUtils The instance of {@link CacheDoubleUtils}.
* @return the bitmap if cache exists or defaultValue otherwise
*/
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | true |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/GsonUtils.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/GsonUtils.java | package com.blankj.utilcode.util;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import androidx.annotation.NonNull;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/04/05
* desc : utils about gson
* </pre>
*/
public final class GsonUtils {
private static final String KEY_DEFAULT = "defaultGson";
private static final String KEY_DELEGATE = "delegateGson";
private static final String KEY_LOG_UTILS = "logUtilsGson";
private static final Map<String, Gson> GSONS = new ConcurrentHashMap<>();
private GsonUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Set the delegate of {@link Gson}.
*
* @param delegate The delegate of {@link Gson}.
*/
public static void setGsonDelegate(Gson delegate) {
if (delegate == null) return;
GSONS.put(KEY_DELEGATE, delegate);
}
/**
* Set the {@link Gson} with key.
*
* @param key The key.
* @param gson The {@link Gson}.
*/
public static void setGson(final String key, final Gson gson) {
if (TextUtils.isEmpty(key) || gson == null) return;
GSONS.put(key, gson);
}
/**
* Return the {@link Gson} with key.
*
* @param key The key.
* @return the {@link Gson} with key
*/
public static Gson getGson(final String key) {
return GSONS.get(key);
}
public static Gson getGson() {
Gson gsonDelegate = GSONS.get(KEY_DELEGATE);
if (gsonDelegate != null) {
return gsonDelegate;
}
Gson gsonDefault = GSONS.get(KEY_DEFAULT);
if (gsonDefault == null) {
gsonDefault = createGson();
GSONS.put(KEY_DEFAULT, gsonDefault);
}
return gsonDefault;
}
/**
* Serializes an object into json.
*
* @param object The object to serialize.
* @return object serialized into json.
*/
public static String toJson(final Object object) {
return toJson(getGson(), object);
}
/**
* Serializes an object into json.
*
* @param src The object to serialize.
* @param typeOfSrc The specific genericized type of src.
* @return object serialized into json.
*/
public static String toJson(final Object src, @NonNull final Type typeOfSrc) {
return toJson(getGson(), src, typeOfSrc);
}
/**
* Serializes an object into json.
*
* @param gson The gson.
* @param object The object to serialize.
* @return object serialized into json.
*/
public static String toJson(@NonNull final Gson gson, final Object object) {
return gson.toJson(object);
}
/**
* Serializes an object into json.
*
* @param gson The gson.
* @param src The object to serialize.
* @param typeOfSrc The specific genericized type of src.
* @return object serialized into json.
*/
public static String toJson(@NonNull final Gson gson, final Object src, @NonNull final Type typeOfSrc) {
return gson.toJson(src, typeOfSrc);
}
/**
* Converts {@link String} to given type.
*
* @param json The json to convert.
* @param type Type json will be converted to.
* @return instance of type
*/
public static <T> T fromJson(final String json, @NonNull final Class<T> type) {
return fromJson(getGson(), json, type);
}
/**
* Converts {@link String} to given type.
*
* @param json the json to convert.
* @param type type type json will be converted to.
* @return instance of type
*/
public static <T> T fromJson(final String json, @NonNull final Type type) {
return fromJson(getGson(), json, type);
}
/**
* Converts {@link Reader} to given type.
*
* @param reader the reader to convert.
* @param type type type json will be converted to.
* @return instance of type
*/
public static <T> T fromJson(@NonNull final Reader reader, @NonNull final Class<T> type) {
return fromJson(getGson(), reader, type);
}
/**
* Converts {@link Reader} to given type.
*
* @param reader the reader to convert.
* @param type type type json will be converted to.
* @return instance of type
*/
public static <T> T fromJson(@NonNull final Reader reader, @NonNull final Type type) {
return fromJson(getGson(), reader, type);
}
/**
* Converts {@link String} to given type.
*
* @param gson The gson.
* @param json The json to convert.
* @param type Type json will be converted to.
* @return instance of type
*/
public static <T> T fromJson(@NonNull final Gson gson, final String json, @NonNull final Class<T> type) {
return gson.fromJson(json, type);
}
/**
* Converts {@link String} to given type.
*
* @param gson The gson.
* @param json the json to convert.
* @param type type type json will be converted to.
* @return instance of type
*/
public static <T> T fromJson(@NonNull final Gson gson, final String json, @NonNull final Type type) {
return gson.fromJson(json, type);
}
/**
* Converts {@link Reader} to given type.
*
* @param gson The gson.
* @param reader the reader to convert.
* @param type type type json will be converted to.
* @return instance of type
*/
public static <T> T fromJson(@NonNull final Gson gson, final Reader reader, @NonNull final Class<T> type) {
return gson.fromJson(reader, type);
}
/**
* Converts {@link Reader} to given type.
*
* @param gson The gson.
* @param reader the reader to convert.
* @param type type type json will be converted to.
* @return instance of type
*/
public static <T> T fromJson(@NonNull final Gson gson, final Reader reader, @NonNull final Type type) {
return gson.fromJson(reader, type);
}
/**
* Return the type of {@link List} with the {@code type}.
*
* @param type The type.
* @return the type of {@link List} with the {@code type}
*/
public static Type getListType(@NonNull final Type type) {
return TypeToken.getParameterized(List.class, type).getType();
}
/**
* Return the type of {@link Set} with the {@code type}.
*
* @param type The type.
* @return the type of {@link Set} with the {@code type}
*/
public static Type getSetType(@NonNull final Type type) {
return TypeToken.getParameterized(Set.class, type).getType();
}
/**
* Return the type of map with the {@code keyType} and {@code valueType}.
*
* @param keyType The type of key.
* @param valueType The type of value.
* @return the type of map with the {@code keyType} and {@code valueType}
*/
public static Type getMapType(@NonNull final Type keyType, @NonNull final Type valueType) {
return TypeToken.getParameterized(Map.class, keyType, valueType).getType();
}
/**
* Return the type of array with the {@code type}.
*
* @param type The type.
* @return the type of map with the {@code type}
*/
public static Type getArrayType(@NonNull final Type type) {
return TypeToken.getArray(type).getType();
}
/**
* Return the type of {@code rawType} with the {@code typeArguments}.
*
* @param rawType The raw type.
* @param typeArguments The type of arguments.
* @return the type of map with the {@code type}
*/
public static Type getType(@NonNull final Type rawType, @NonNull final Type... typeArguments) {
return TypeToken.getParameterized(rawType, typeArguments).getType();
}
static Gson getGson4LogUtils() {
Gson gson4LogUtils = GSONS.get(KEY_LOG_UTILS);
if (gson4LogUtils == null) {
gson4LogUtils = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
GSONS.put(KEY_LOG_UTILS, gson4LogUtils);
}
return gson4LogUtils;
}
private static Gson createGson() {
return new GsonBuilder().serializeNulls().disableHtmlEscaping().create();
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/UtilsTransActivity4MainProcess.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/UtilsTransActivity4MainProcess.java | package com.blankj.utilcode.util;
import android.app.Activity;
import android.content.Intent;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2020/03/19
* desc :
* </pre>
*/
public class UtilsTransActivity4MainProcess extends UtilsTransActivity {
public static void start(final TransActivityDelegate delegate) {
start(null, null, delegate, UtilsTransActivity4MainProcess.class);
}
public static void start(final Utils.Consumer<Intent> consumer,
final TransActivityDelegate delegate) {
start(null, consumer, delegate, UtilsTransActivity4MainProcess.class);
}
public static void start(final Activity activity,
final TransActivityDelegate delegate) {
start(activity, null, delegate, UtilsTransActivity4MainProcess.class);
}
public static void start(final Activity activity,
final Utils.Consumer<Intent> consumer,
final TransActivityDelegate delegate) {
start(activity, consumer, delegate, UtilsTransActivity4MainProcess.class);
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/FileIOUtils.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/FileIOUtils.java | package com.blankj.utilcode.util;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/06/22
* desc : utils about file io
* </pre>
*/
public final class FileIOUtils {
private static int sBufferSize = 524288;
private FileIOUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
///////////////////////////////////////////////////////////////////////////
// writeFileFromIS without progress
///////////////////////////////////////////////////////////////////////////
/**
* Write file from input stream.
*
* @param filePath The path of file.
* @param is The input stream.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromIS(final String filePath, final InputStream is) {
return writeFileFromIS(UtilsBridge.getFileByPath(filePath), is, false, null);
}
/**
* Write file from input stream.
*
* @param filePath The path of file.
* @param is The input stream.
* @param append True to append, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromIS(final String filePath,
final InputStream is,
final boolean append) {
return writeFileFromIS(UtilsBridge.getFileByPath(filePath), is, append, null);
}
/**
* Write file from input stream.
*
* @param file The file.
* @param is The input stream.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromIS(final File file, final InputStream is) {
return writeFileFromIS(file, is, false, null);
}
/**
* Write file from input stream.
*
* @param file The file.
* @param is The input stream.
* @param append True to append, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromIS(final File file,
final InputStream is,
final boolean append) {
return writeFileFromIS(file, is, append, null);
}
///////////////////////////////////////////////////////////////////////////
// writeFileFromIS with progress
///////////////////////////////////////////////////////////////////////////
/**
* Write file from input stream.
*
* @param filePath The path of file.
* @param is The input stream.
* @param listener The progress update listener.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromIS(final String filePath,
final InputStream is,
final OnProgressUpdateListener listener) {
return writeFileFromIS(UtilsBridge.getFileByPath(filePath), is, false, listener);
}
/**
* Write file from input stream.
*
* @param filePath The path of file.
* @param is The input stream.
* @param append True to append, false otherwise.
* @param listener The progress update listener.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromIS(final String filePath,
final InputStream is,
final boolean append,
final OnProgressUpdateListener listener) {
return writeFileFromIS(UtilsBridge.getFileByPath(filePath), is, append, listener);
}
/**
* Write file from input stream.
*
* @param file The file.
* @param is The input stream.
* @param listener The progress update listener.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromIS(final File file,
final InputStream is,
final OnProgressUpdateListener listener) {
return writeFileFromIS(file, is, false, listener);
}
/**
* Write file from input stream.
*
* @param file The file.
* @param is The input stream.
* @param append True to append, false otherwise.
* @param listener The progress update listener.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromIS(final File file,
final InputStream is,
final boolean append,
final OnProgressUpdateListener listener) {
if (is == null || !UtilsBridge.createOrExistsFile(file)) {
Log.e("FileIOUtils", "create file <" + file + "> failed.");
return false;
}
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file, append), sBufferSize);
if (listener == null) {
byte[] data = new byte[sBufferSize];
for (int len; (len = is.read(data)) != -1; ) {
os.write(data, 0, len);
}
} else {
double totalSize = is.available();
int curSize = 0;
listener.onProgressUpdate(0);
byte[] data = new byte[sBufferSize];
for (int len; (len = is.read(data)) != -1; ) {
os.write(data, 0, len);
curSize += len;
listener.onProgressUpdate(curSize / totalSize);
}
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
///////////////////////////////////////////////////////////////////////////
// writeFileFromBytesByStream without progress
///////////////////////////////////////////////////////////////////////////
/**
* Write file from bytes by stream.
*
* @param filePath The path of file.
* @param bytes The bytes.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByStream(final String filePath, final byte[] bytes) {
return writeFileFromBytesByStream(UtilsBridge.getFileByPath(filePath), bytes, false, null);
}
/**
* Write file from bytes by stream.
*
* @param filePath The path of file.
* @param bytes The bytes.
* @param append True to append, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByStream(final String filePath,
final byte[] bytes,
final boolean append) {
return writeFileFromBytesByStream(UtilsBridge.getFileByPath(filePath), bytes, append, null);
}
/**
* Write file from bytes by stream.
*
* @param file The file.
* @param bytes The bytes.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByStream(final File file, final byte[] bytes) {
return writeFileFromBytesByStream(file, bytes, false, null);
}
/**
* Write file from bytes by stream.
*
* @param file The file.
* @param bytes The bytes.
* @param append True to append, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByStream(final File file,
final byte[] bytes,
final boolean append) {
return writeFileFromBytesByStream(file, bytes, append, null);
}
///////////////////////////////////////////////////////////////////////////
// writeFileFromBytesByStream with progress
///////////////////////////////////////////////////////////////////////////
/**
* Write file from bytes by stream.
*
* @param filePath The path of file.
* @param bytes The bytes.
* @param listener The progress update listener.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByStream(final String filePath,
final byte[] bytes,
final OnProgressUpdateListener listener) {
return writeFileFromBytesByStream(UtilsBridge.getFileByPath(filePath), bytes, false, listener);
}
/**
* Write file from bytes by stream.
*
* @param filePath The path of file.
* @param bytes The bytes.
* @param append True to append, false otherwise.
* @param listener The progress update listener.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByStream(final String filePath,
final byte[] bytes,
final boolean append,
final OnProgressUpdateListener listener) {
return writeFileFromBytesByStream(UtilsBridge.getFileByPath(filePath), bytes, append, listener);
}
/**
* Write file from bytes by stream.
*
* @param file The file.
* @param bytes The bytes.
* @param listener The progress update listener.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByStream(final File file,
final byte[] bytes,
final OnProgressUpdateListener listener) {
return writeFileFromBytesByStream(file, bytes, false, listener);
}
/**
* Write file from bytes by stream.
*
* @param file The file.
* @param bytes The bytes.
* @param append True to append, false otherwise.
* @param listener The progress update listener.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByStream(final File file,
final byte[] bytes,
final boolean append,
final OnProgressUpdateListener listener) {
if (bytes == null) return false;
return writeFileFromIS(file, new ByteArrayInputStream(bytes), append, listener);
}
/**
* Write file from bytes by channel.
*
* @param filePath The path of file.
* @param bytes The bytes.
* @param isForce 是否写入文件
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByChannel(final String filePath,
final byte[] bytes,
final boolean isForce) {
return writeFileFromBytesByChannel(UtilsBridge.getFileByPath(filePath), bytes, false, isForce);
}
/**
* Write file from bytes by channel.
*
* @param filePath The path of file.
* @param bytes The bytes.
* @param append True to append, false otherwise.
* @param isForce True to force write file, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByChannel(final String filePath,
final byte[] bytes,
final boolean append,
final boolean isForce) {
return writeFileFromBytesByChannel(UtilsBridge.getFileByPath(filePath), bytes, append, isForce);
}
/**
* Write file from bytes by channel.
*
* @param file The file.
* @param bytes The bytes.
* @param isForce True to force write file, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByChannel(final File file,
final byte[] bytes,
final boolean isForce) {
return writeFileFromBytesByChannel(file, bytes, false, isForce);
}
/**
* Write file from bytes by channel.
*
* @param file The file.
* @param bytes The bytes.
* @param append True to append, false otherwise.
* @param isForce True to force write file, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByChannel(final File file,
final byte[] bytes,
final boolean append,
final boolean isForce) {
if (bytes == null) {
Log.e("FileIOUtils", "bytes is null.");
return false;
}
if (!UtilsBridge.createOrExistsFile(file)) {
Log.e("FileIOUtils", "create file <" + file + "> failed.");
return false;
}
FileChannel fc = null;
try {
fc = new FileOutputStream(file, append).getChannel();
if (fc == null) {
Log.e("FileIOUtils", "fc is null.");
return false;
}
fc.position(fc.size());
fc.write(ByteBuffer.wrap(bytes));
if (isForce) fc.force(true);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (fc != null) {
fc.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Write file from bytes by map.
*
* @param filePath The path of file.
* @param bytes The bytes.
* @param isForce True to force write file, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByMap(final String filePath,
final byte[] bytes,
final boolean isForce) {
return writeFileFromBytesByMap(filePath, bytes, false, isForce);
}
/**
* Write file from bytes by map.
*
* @param filePath The path of file.
* @param bytes The bytes.
* @param append True to append, false otherwise.
* @param isForce True to force write file, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByMap(final String filePath,
final byte[] bytes,
final boolean append,
final boolean isForce) {
return writeFileFromBytesByMap(UtilsBridge.getFileByPath(filePath), bytes, append, isForce);
}
/**
* Write file from bytes by map.
*
* @param file The file.
* @param bytes The bytes.
* @param isForce True to force write file, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByMap(final File file,
final byte[] bytes,
final boolean isForce) {
return writeFileFromBytesByMap(file, bytes, false, isForce);
}
/**
* Write file from bytes by map.
*
* @param file The file.
* @param bytes The bytes.
* @param append True to append, false otherwise.
* @param isForce True to force write file, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromBytesByMap(final File file,
final byte[] bytes,
final boolean append,
final boolean isForce) {
if (bytes == null || !UtilsBridge.createOrExistsFile(file)) {
Log.e("FileIOUtils", "create file <" + file + "> failed.");
return false;
}
FileChannel fc = null;
try {
fc = new FileOutputStream(file, append).getChannel();
if (fc == null) {
Log.e("FileIOUtils", "fc is null.");
return false;
}
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, fc.size(), bytes.length);
mbb.put(bytes);
if (isForce) mbb.force();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (fc != null) {
fc.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Write file from string.
*
* @param filePath The path of file.
* @param content The string of content.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromString(final String filePath, final String content) {
return writeFileFromString(UtilsBridge.getFileByPath(filePath), content, false);
}
/**
* Write file from string.
*
* @param filePath The path of file.
* @param content The string of content.
* @param append True to append, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromString(final String filePath,
final String content,
final boolean append) {
return writeFileFromString(UtilsBridge.getFileByPath(filePath), content, append);
}
/**
* Write file from string.
*
* @param file The file.
* @param content The string of content.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromString(final File file, final String content) {
return writeFileFromString(file, content, false);
}
/**
* Write file from string.
*
* @param file The file.
* @param content The string of content.
* @param append True to append, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean writeFileFromString(final File file,
final String content,
final boolean append) {
if (file == null || content == null) return false;
if (!UtilsBridge.createOrExistsFile(file)) {
Log.e("FileIOUtils", "create file <" + file + "> failed.");
return false;
}
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(file, append));
bw.write(content);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
///////////////////////////////////////////////////////////////////////////
// the divide line of write and read
///////////////////////////////////////////////////////////////////////////
/**
* Return the lines in file.
*
* @param filePath The path of file.
* @return the lines in file
*/
public static List<String> readFile2List(final String filePath) {
return readFile2List(UtilsBridge.getFileByPath(filePath), null);
}
/**
* Return the lines in file.
*
* @param filePath The path of file.
* @param charsetName The name of charset.
* @return the lines in file
*/
public static List<String> readFile2List(final String filePath, final String charsetName) {
return readFile2List(UtilsBridge.getFileByPath(filePath), charsetName);
}
/**
* Return the lines in file.
*
* @param file The file.
* @return the lines in file
*/
public static List<String> readFile2List(final File file) {
return readFile2List(file, 0, 0x7FFFFFFF, null);
}
/**
* Return the lines in file.
*
* @param file The file.
* @param charsetName The name of charset.
* @return the lines in file
*/
public static List<String> readFile2List(final File file, final String charsetName) {
return readFile2List(file, 0, 0x7FFFFFFF, charsetName);
}
/**
* Return the lines in file.
*
* @param filePath The path of file.
* @param st The line's index of start.
* @param end The line's index of end.
* @return the lines in file
*/
public static List<String> readFile2List(final String filePath, final int st, final int end) {
return readFile2List(UtilsBridge.getFileByPath(filePath), st, end, null);
}
/**
* Return the lines in file.
*
* @param filePath The path of file.
* @param st The line's index of start.
* @param end The line's index of end.
* @param charsetName The name of charset.
* @return the lines in file
*/
public static List<String> readFile2List(final String filePath,
final int st,
final int end,
final String charsetName) {
return readFile2List(UtilsBridge.getFileByPath(filePath), st, end, charsetName);
}
/**
* Return the lines in file.
*
* @param file The file.
* @param st The line's index of start.
* @param end The line's index of end.
* @return the lines in file
*/
public static List<String> readFile2List(final File file, final int st, final int end) {
return readFile2List(file, st, end, null);
}
/**
* Return the lines in file.
*
* @param file The file.
* @param st The line's index of start.
* @param end The line's index of end.
* @param charsetName The name of charset.
* @return the lines in file
*/
public static List<String> readFile2List(final File file,
final int st,
final int end,
final String charsetName) {
if (!UtilsBridge.isFileExists(file)) return null;
if (st > end) return null;
BufferedReader reader = null;
try {
String line;
int curLine = 1;
List<String> list = new ArrayList<>();
if (UtilsBridge.isSpace(charsetName)) {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
} else {
reader = new BufferedReader(
new InputStreamReader(new FileInputStream(file), charsetName)
);
}
while ((line = reader.readLine()) != null) {
if (curLine > end) break;
if (st <= curLine && curLine <= end) list.add(line);
++curLine;
}
return list;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Return the string in file.
*
* @param filePath The path of file.
* @return the string in file
*/
public static String readFile2String(final String filePath) {
return readFile2String(UtilsBridge.getFileByPath(filePath), null);
}
/**
* Return the string in file.
*
* @param filePath The path of file.
* @param charsetName The name of charset.
* @return the string in file
*/
public static String readFile2String(final String filePath, final String charsetName) {
return readFile2String(UtilsBridge.getFileByPath(filePath), charsetName);
}
/**
* Return the string in file.
*
* @param file The file.
* @return the string in file
*/
public static String readFile2String(final File file) {
return readFile2String(file, null);
}
/**
* Return the string in file.
*
* @param file The file.
* @param charsetName The name of charset.
* @return the string in file
*/
public static String readFile2String(final File file, final String charsetName) {
byte[] bytes = readFile2BytesByStream(file);
if (bytes == null) return null;
if (UtilsBridge.isSpace(charsetName)) {
return new String(bytes);
} else {
try {
return new String(bytes, charsetName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
}
///////////////////////////////////////////////////////////////////////////
// readFile2BytesByStream without progress
///////////////////////////////////////////////////////////////////////////
/**
* Return the bytes in file by stream.
*
* @param filePath The path of file.
* @return the bytes in file
*/
public static byte[] readFile2BytesByStream(final String filePath) {
return readFile2BytesByStream(UtilsBridge.getFileByPath(filePath), null);
}
/**
* Return the bytes in file by stream.
*
* @param file The file.
* @return the bytes in file
*/
public static byte[] readFile2BytesByStream(final File file) {
return readFile2BytesByStream(file, null);
}
///////////////////////////////////////////////////////////////////////////
// readFile2BytesByStream with progress
///////////////////////////////////////////////////////////////////////////
/**
* Return the bytes in file by stream.
*
* @param filePath The path of file.
* @param listener The progress update listener.
* @return the bytes in file
*/
public static byte[] readFile2BytesByStream(final String filePath,
final OnProgressUpdateListener listener) {
return readFile2BytesByStream(UtilsBridge.getFileByPath(filePath), listener);
}
/**
* Return the bytes in file by stream.
*
* @param file The file.
* @param listener The progress update listener.
* @return the bytes in file
*/
public static byte[] readFile2BytesByStream(final File file,
final OnProgressUpdateListener listener) {
if (!UtilsBridge.isFileExists(file)) return null;
try {
ByteArrayOutputStream os = null;
InputStream is = new BufferedInputStream(new FileInputStream(file), sBufferSize);
try {
os = new ByteArrayOutputStream();
byte[] b = new byte[sBufferSize];
int len;
if (listener == null) {
while ((len = is.read(b, 0, sBufferSize)) != -1) {
os.write(b, 0, len);
}
} else {
double totalSize = is.available();
int curSize = 0;
listener.onProgressUpdate(0);
while ((len = is.read(b, 0, sBufferSize)) != -1) {
os.write(b, 0, len);
curSize += len;
listener.onProgressUpdate(curSize / totalSize);
}
}
return os.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* Return the bytes in file by channel.
*
* @param filePath The path of file.
* @return the bytes in file
*/
public static byte[] readFile2BytesByChannel(final String filePath) {
return readFile2BytesByChannel(UtilsBridge.getFileByPath(filePath));
}
/**
* Return the bytes in file by channel.
*
* @param file The file.
* @return the bytes in file
*/
public static byte[] readFile2BytesByChannel(final File file) {
if (!UtilsBridge.isFileExists(file)) return null;
FileChannel fc = null;
try {
fc = new RandomAccessFile(file, "r").getChannel();
if (fc == null) {
Log.e("FileIOUtils", "fc is null.");
return new byte[0];
}
ByteBuffer byteBuffer = ByteBuffer.allocate((int) fc.size());
while (true) {
if (!((fc.read(byteBuffer)) > 0)) break;
}
return byteBuffer.array();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (fc != null) {
fc.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Return the bytes in file by map.
*
* @param filePath The path of file.
* @return the bytes in file
*/
public static byte[] readFile2BytesByMap(final String filePath) {
return readFile2BytesByMap(UtilsBridge.getFileByPath(filePath));
}
/**
* Return the bytes in file by map.
*
* @param file The file.
* @return the bytes in file
*/
public static byte[] readFile2BytesByMap(final File file) {
if (!UtilsBridge.isFileExists(file)) return null;
FileChannel fc = null;
try {
fc = new RandomAccessFile(file, "r").getChannel();
if (fc == null) {
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | true |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/UtilsFileProvider.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/UtilsFileProvider.java | package com.blankj.utilcode.util;
import android.app.Application;
import androidx.core.content.FileProvider;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2020/03/19
* desc :
* </pre>
*/
public class UtilsFileProvider extends FileProvider {
@Override
public boolean onCreate() {
//noinspection ConstantConditions
Utils.init((Application) getContext().getApplicationContext());
return true;
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/SPStaticUtils.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/SPStaticUtils.java | package com.blankj.utilcode.util;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import java.util.Map;
import java.util.Set;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/01/04
* desc : utils about shared preference
* </pre>
*/
public final class SPStaticUtils {
private static SPUtils sDefaultSPUtils;
/**
* Set the default instance of {@link SPUtils}.
*
* @param spUtils The default instance of {@link SPUtils}.
*/
public static void setDefaultSPUtils(final SPUtils spUtils) {
sDefaultSPUtils = spUtils;
}
/**
* Put the string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public static void put(@NonNull final String key, final String value) {
put(key, value, getDefaultSPUtils());
}
/**
* Put the string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public static void put(@NonNull final String key, final String value, final boolean isCommit) {
put(key, value, isCommit, getDefaultSPUtils());
}
/**
* Return the string value in sp.
*
* @param key The key of sp.
* @return the string value if sp exists or {@code ""} otherwise
*/
public static String getString(@NonNull final String key) {
return getString(key, getDefaultSPUtils());
}
/**
* Return the string value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the string value if sp exists or {@code defaultValue} otherwise
*/
public static String getString(@NonNull final String key, final String defaultValue) {
return getString(key, defaultValue, getDefaultSPUtils());
}
/**
* Put the int value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public static void put(@NonNull final String key, final int value) {
put(key, value, getDefaultSPUtils());
}
/**
* Put the int value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public static void put(@NonNull final String key, final int value, final boolean isCommit) {
put(key, value, isCommit, getDefaultSPUtils());
}
/**
* Return the int value in sp.
*
* @param key The key of sp.
* @return the int value if sp exists or {@code -1} otherwise
*/
public static int getInt(@NonNull final String key) {
return getInt(key, getDefaultSPUtils());
}
/**
* Return the int value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the int value if sp exists or {@code defaultValue} otherwise
*/
public static int getInt(@NonNull final String key, final int defaultValue) {
return getInt(key, defaultValue, getDefaultSPUtils());
}
/**
* Put the long value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public static void put(@NonNull final String key, final long value) {
put(key, value, getDefaultSPUtils());
}
/**
* Put the long value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public static void put(@NonNull final String key, final long value, final boolean isCommit) {
put(key, value, isCommit, getDefaultSPUtils());
}
/**
* Return the long value in sp.
*
* @param key The key of sp.
* @return the long value if sp exists or {@code -1} otherwise
*/
public static long getLong(@NonNull final String key) {
return getLong(key, getDefaultSPUtils());
}
/**
* Return the long value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the long value if sp exists or {@code defaultValue} otherwise
*/
public static long getLong(@NonNull final String key, final long defaultValue) {
return getLong(key, defaultValue, getDefaultSPUtils());
}
/**
* Put the float value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public static void put(@NonNull final String key, final float value) {
put(key, value, getDefaultSPUtils());
}
/**
* Put the float value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public static void put(@NonNull final String key, final float value, final boolean isCommit) {
put(key, value, isCommit, getDefaultSPUtils());
}
/**
* Return the float value in sp.
*
* @param key The key of sp.
* @return the float value if sp exists or {@code -1f} otherwise
*/
public static float getFloat(@NonNull final String key) {
return getFloat(key, getDefaultSPUtils());
}
/**
* Return the float value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the float value if sp exists or {@code defaultValue} otherwise
*/
public static float getFloat(@NonNull final String key, final float defaultValue) {
return getFloat(key, defaultValue, getDefaultSPUtils());
}
/**
* Put the boolean value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public static void put(@NonNull final String key, final boolean value) {
put(key, value, getDefaultSPUtils());
}
/**
* Put the boolean value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public static void put(@NonNull final String key, final boolean value, final boolean isCommit) {
put(key, value, isCommit, getDefaultSPUtils());
}
/**
* Return the boolean value in sp.
*
* @param key The key of sp.
* @return the boolean value if sp exists or {@code false} otherwise
*/
public static boolean getBoolean(@NonNull final String key) {
return getBoolean(key, getDefaultSPUtils());
}
/**
* Return the boolean value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the boolean value if sp exists or {@code defaultValue} otherwise
*/
public static boolean getBoolean(@NonNull final String key, final boolean defaultValue) {
return getBoolean(key, defaultValue, getDefaultSPUtils());
}
/**
* Put the set of string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
*/
public static void put(@NonNull final String key, final Set<String> value) {
put(key, value, getDefaultSPUtils());
}
/**
* Put the set of string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public static void put(@NonNull final String key,
final Set<String> value,
final boolean isCommit) {
put(key, value, isCommit, getDefaultSPUtils());
}
/**
* Return the set of string value in sp.
*
* @param key The key of sp.
* @return the set of string value if sp exists
* or {@code Collections.<String>emptySet()} otherwise
*/
public static Set<String> getStringSet(@NonNull final String key) {
return getStringSet(key, getDefaultSPUtils());
}
/**
* Return the set of string value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @return the set of string value if sp exists or {@code defaultValue} otherwise
*/
public static Set<String> getStringSet(@NonNull final String key,
final Set<String> defaultValue) {
return getStringSet(key, defaultValue, getDefaultSPUtils());
}
/**
* Return all values in sp.
*
* @return all values in sp
*/
public static Map<String, ?> getAll() {
return getAll(getDefaultSPUtils());
}
/**
* Return whether the sp contains the preference.
*
* @param key The key of sp.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean contains(@NonNull final String key) {
return contains(key, getDefaultSPUtils());
}
/**
* Remove the preference in sp.
*
* @param key The key of sp.
*/
public static void remove(@NonNull final String key) {
remove(key, getDefaultSPUtils());
}
/**
* Remove the preference in sp.
*
* @param key The key of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public static void remove(@NonNull final String key, final boolean isCommit) {
remove(key, isCommit, getDefaultSPUtils());
}
/**
* Remove all preferences in sp.
*/
public static void clear() {
clear(getDefaultSPUtils());
}
/**
* Remove all preferences in sp.
*
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
*/
public static void clear(final boolean isCommit) {
clear(isCommit, getDefaultSPUtils());
}
///////////////////////////////////////////////////////////////////////////
// dividing line
///////////////////////////////////////////////////////////////////////////
/**
* Put the string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key, final String value, @NonNull final SPUtils spUtils) {
spUtils.put(key, value);
}
/**
* Put the string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key,
final String value,
final boolean isCommit,
@NonNull final SPUtils spUtils) {
spUtils.put(key, value, isCommit);
}
/**
* Return the string value in sp.
*
* @param key The key of sp.
* @param spUtils The instance of {@link SPUtils}.
* @return the string value if sp exists or {@code ""} otherwise
*/
public static String getString(@NonNull final String key, @NonNull final SPUtils spUtils) {
return spUtils.getString(key);
}
/**
* Return the string value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @param spUtils The instance of {@link SPUtils}.
* @return the string value if sp exists or {@code defaultValue} otherwise
*/
public static String getString(@NonNull final String key,
final String defaultValue,
@NonNull final SPUtils spUtils) {
return spUtils.getString(key, defaultValue);
}
/**
* Put the int value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key, final int value, @NonNull final SPUtils spUtils) {
spUtils.put(key, value);
}
/**
* Put the int value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key,
final int value,
final boolean isCommit,
@NonNull final SPUtils spUtils) {
spUtils.put(key, value, isCommit);
}
/**
* Return the int value in sp.
*
* @param key The key of sp.
* @param spUtils The instance of {@link SPUtils}.
* @return the int value if sp exists or {@code -1} otherwise
*/
public static int getInt(@NonNull final String key, @NonNull final SPUtils spUtils) {
return spUtils.getInt(key);
}
/**
* Return the int value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @param spUtils The instance of {@link SPUtils}.
* @return the int value if sp exists or {@code defaultValue} otherwise
*/
public static int getInt(@NonNull final String key, final int defaultValue, @NonNull final SPUtils spUtils) {
return spUtils.getInt(key, defaultValue);
}
/**
* Put the long value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key, final long value, @NonNull final SPUtils spUtils) {
spUtils.put(key, value);
}
/**
* Put the long value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key,
final long value,
final boolean isCommit,
@NonNull final SPUtils spUtils) {
spUtils.put(key, value, isCommit);
}
/**
* Return the long value in sp.
*
* @param key The key of sp.
* @param spUtils The instance of {@link SPUtils}.
* @return the long value if sp exists or {@code -1} otherwise
*/
public static long getLong(@NonNull final String key, @NonNull final SPUtils spUtils) {
return spUtils.getLong(key);
}
/**
* Return the long value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @param spUtils The instance of {@link SPUtils}.
* @return the long value if sp exists or {@code defaultValue} otherwise
*/
public static long getLong(@NonNull final String key, final long defaultValue, @NonNull final SPUtils spUtils) {
return spUtils.getLong(key, defaultValue);
}
/**
* Put the float value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key, final float value, @NonNull final SPUtils spUtils) {
spUtils.put(key, value);
}
/**
* Put the float value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key,
final float value,
final boolean isCommit,
@NonNull final SPUtils spUtils) {
spUtils.put(key, value, isCommit);
}
/**
* Return the float value in sp.
*
* @param key The key of sp.
* @param spUtils The instance of {@link SPUtils}.
* @return the float value if sp exists or {@code -1f} otherwise
*/
public static float getFloat(@NonNull final String key, @NonNull final SPUtils spUtils) {
return spUtils.getFloat(key);
}
/**
* Return the float value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @param spUtils The instance of {@link SPUtils}.
* @return the float value if sp exists or {@code defaultValue} otherwise
*/
public static float getFloat(@NonNull final String key, final float defaultValue, @NonNull final SPUtils spUtils) {
return spUtils.getFloat(key, defaultValue);
}
/**
* Put the boolean value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key, final boolean value, @NonNull final SPUtils spUtils) {
spUtils.put(key, value);
}
/**
* Put the boolean value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key,
final boolean value,
final boolean isCommit,
@NonNull final SPUtils spUtils) {
spUtils.put(key, value, isCommit);
}
/**
* Return the boolean value in sp.
*
* @param key The key of sp.
* @param spUtils The instance of {@link SPUtils}.
* @return the boolean value if sp exists or {@code false} otherwise
*/
public static boolean getBoolean(@NonNull final String key, @NonNull final SPUtils spUtils) {
return spUtils.getBoolean(key);
}
/**
* Return the boolean value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @param spUtils The instance of {@link SPUtils}.
* @return the boolean value if sp exists or {@code defaultValue} otherwise
*/
public static boolean getBoolean(@NonNull final String key,
final boolean defaultValue,
@NonNull final SPUtils spUtils) {
return spUtils.getBoolean(key, defaultValue);
}
/**
* Put the set of string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key, final Set<String> value, @NonNull final SPUtils spUtils) {
spUtils.put(key, value);
}
/**
* Put the set of string value in sp.
*
* @param key The key of sp.
* @param value The value of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
* @param spUtils The instance of {@link SPUtils}.
*/
public static void put(@NonNull final String key,
final Set<String> value,
final boolean isCommit,
@NonNull final SPUtils spUtils) {
spUtils.put(key, value, isCommit);
}
/**
* Return the set of string value in sp.
*
* @param key The key of sp.
* @param spUtils The instance of {@link SPUtils}.
* @return the set of string value if sp exists
* or {@code Collections.<String>emptySet()} otherwise
*/
public static Set<String> getStringSet(@NonNull final String key, @NonNull final SPUtils spUtils) {
return spUtils.getStringSet(key);
}
/**
* Return the set of string value in sp.
*
* @param key The key of sp.
* @param defaultValue The default value if the sp doesn't exist.
* @param spUtils The instance of {@link SPUtils}.
* @return the set of string value if sp exists or {@code defaultValue} otherwise
*/
public static Set<String> getStringSet(@NonNull final String key,
final Set<String> defaultValue,
@NonNull final SPUtils spUtils) {
return spUtils.getStringSet(key, defaultValue);
}
/**
* Return all values in sp.
*
* @param spUtils The instance of {@link SPUtils}.
* @return all values in sp
*/
public static Map<String, ?> getAll(@NonNull final SPUtils spUtils) {
return spUtils.getAll();
}
/**
* Return whether the sp contains the preference.
*
* @param key The key of sp.
* @param spUtils The instance of {@link SPUtils}.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean contains(@NonNull final String key, @NonNull final SPUtils spUtils) {
return spUtils.contains(key);
}
/**
* Remove the preference in sp.
*
* @param key The key of sp.
* @param spUtils The instance of {@link SPUtils}.
*/
public static void remove(@NonNull final String key, @NonNull final SPUtils spUtils) {
spUtils.remove(key);
}
/**
* Remove the preference in sp.
*
* @param key The key of sp.
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
* @param spUtils The instance of {@link SPUtils}.
*/
public static void remove(@NonNull final String key, final boolean isCommit, @NonNull final SPUtils spUtils) {
spUtils.remove(key, isCommit);
}
/**
* Remove all preferences in sp.
*
* @param spUtils The instance of {@link SPUtils}.
*/
public static void clear(@NonNull final SPUtils spUtils) {
spUtils.clear();
}
/**
* Remove all preferences in sp.
*
* @param isCommit True to use {@link SharedPreferences.Editor#commit()},
* false to use {@link SharedPreferences.Editor#apply()}
* @param spUtils The instance of {@link SPUtils}.
*/
public static void clear(final boolean isCommit, @NonNull final SPUtils spUtils) {
spUtils.clear(isCommit);
}
private static SPUtils getDefaultSPUtils() {
return sDefaultSPUtils != null ? sDefaultSPUtils : SPUtils.getInstance();
}
} | java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/LanguageUtils.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/LanguageUtils.java | package com.blankj.utilcode.util;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import java.util.Locale;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/06/20
* desc : utils about language
* </pre>
*/
public class LanguageUtils {
private static final String KEY_LOCALE = "KEY_LOCALE";
private static final String VALUE_FOLLOW_SYSTEM = "VALUE_FOLLOW_SYSTEM";
private LanguageUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Apply the system language.
*/
public static void applySystemLanguage() {
applySystemLanguage(false);
}
/**
* Apply the system language.
*
* @param isRelaunchApp True to relaunch app, false to recreate all activities.
*/
public static void applySystemLanguage(final boolean isRelaunchApp) {
applyLanguageReal(null, isRelaunchApp);
}
/**
* Apply the language.
*
* @param locale The language of locale.
*/
public static void applyLanguage(@NonNull final Locale locale) {
applyLanguage(locale, false);
}
/**
* Apply the language.
*
* @param locale The language of locale.
* @param isRelaunchApp True to relaunch app, false to recreate all activities.
*/
public static void applyLanguage(@NonNull final Locale locale,
final boolean isRelaunchApp) {
applyLanguageReal(locale, isRelaunchApp);
}
private static void applyLanguageReal(final Locale locale,
final boolean isRelaunchApp) {
if (locale == null) {
UtilsBridge.getSpUtils4Utils().put(KEY_LOCALE, VALUE_FOLLOW_SYSTEM, true);
} else {
UtilsBridge.getSpUtils4Utils().put(KEY_LOCALE, locale2String(locale), true);
}
Locale destLocal = locale == null ? getLocal(Resources.getSystem().getConfiguration()) : locale;
updateAppContextLanguage(destLocal, new Utils.Consumer<Boolean>() {
@Override
public void accept(Boolean success) {
if (success) {
restart(isRelaunchApp);
} else {
// use relaunch app
UtilsBridge.relaunchApp();
}
}
});
}
private static void restart(final boolean isRelaunchApp) {
if (isRelaunchApp) {
UtilsBridge.relaunchApp();
} else {
for (Activity activity : UtilsBridge.getActivityList()) {
activity.recreate();
}
}
}
/**
* Return whether applied the language by {@link LanguageUtils}.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isAppliedLanguage() {
return getAppliedLanguage() != null;
}
/**
* Return whether applied the language by {@link LanguageUtils}.
*
* @param locale The locale.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isAppliedLanguage(@NonNull Locale locale) {
Locale appliedLocale = getAppliedLanguage();
if (appliedLocale == null) {
return false;
}
return isSameLocale(locale, appliedLocale);
}
/**
* Return the applied locale.
*
* @return the applied locale
*/
public static Locale getAppliedLanguage() {
final String spLocaleStr = UtilsBridge.getSpUtils4Utils().getString(KEY_LOCALE);
if (TextUtils.isEmpty(spLocaleStr) || VALUE_FOLLOW_SYSTEM.equals(spLocaleStr)) {
return null;
}
return string2Locale(spLocaleStr);
}
/**
* Return the locale of context.
*
* @return the locale of context
*/
public static Locale getContextLanguage(Context context) {
return getLocal(context.getResources().getConfiguration());
}
/**
* Return the locale of applicationContext.
*
* @return the locale of applicationContext
*/
public static Locale getAppContextLanguage() {
return getContextLanguage(Utils.getApp());
}
/**
* Return the locale of system
*
* @return the locale of system
*/
public static Locale getSystemLanguage() {
return getLocal(Resources.getSystem().getConfiguration());
}
/**
* Update the locale of applicationContext.
*
* @param destLocale The dest locale.
* @param consumer The consumer.
*/
public static void updateAppContextLanguage(@NonNull Locale destLocale, @Nullable Utils.Consumer<Boolean> consumer) {
pollCheckAppContextLocal(destLocale, 0, consumer);
}
static void pollCheckAppContextLocal(final Locale destLocale, final int index, final Utils.Consumer<Boolean> consumer) {
Resources appResources = Utils.getApp().getResources();
Configuration appConfig = appResources.getConfiguration();
Locale appLocal = getLocal(appConfig);
setLocal(appConfig, destLocale);
Utils.getApp().getResources().updateConfiguration(appConfig, appResources.getDisplayMetrics());
if (consumer == null) return;
if (isSameLocale(appLocal, destLocale)) {
consumer.accept(true);
} else {
if (index < 20) {
UtilsBridge.runOnUiThreadDelayed(new Runnable() {
@Override
public void run() {
pollCheckAppContextLocal(destLocale, index + 1, consumer);
}
}, 16);
return;
}
Log.e("LanguageUtils", "appLocal didn't update.");
consumer.accept(false);
}
}
/**
* If applyLanguage not work, try to call it in {@link Activity#attachBaseContext(Context)}.
*
* @param context The baseContext.
* @return the context with language
*/
public static Context attachBaseContext(Context context) {
String spLocaleStr = UtilsBridge.getSpUtils4Utils().getString(KEY_LOCALE);
if (TextUtils.isEmpty(spLocaleStr) || VALUE_FOLLOW_SYSTEM.equals(spLocaleStr)) {
return context;
}
Locale settingsLocale = string2Locale(spLocaleStr);
if (settingsLocale == null) return context;
Resources resources = context.getResources();
Configuration config = resources.getConfiguration();
setLocal(config, settingsLocale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return context.createConfigurationContext(config);
} else {
resources.updateConfiguration(config, resources.getDisplayMetrics());
return context;
}
}
static void applyLanguage(final Activity activity) {
String spLocale = UtilsBridge.getSpUtils4Utils().getString(KEY_LOCALE);
if (TextUtils.isEmpty(spLocale)) {
return;
}
Locale destLocal;
if (VALUE_FOLLOW_SYSTEM.equals(spLocale)) {
destLocal = getLocal(Resources.getSystem().getConfiguration());
} else {
destLocal = string2Locale(spLocale);
}
if (destLocal == null) return;
updateConfiguration(activity, destLocal);
updateConfiguration(Utils.getApp(), destLocal);
}
private static void updateConfiguration(Context context, Locale destLocal) {
Resources resources = context.getResources();
Configuration config = resources.getConfiguration();
setLocal(config, destLocal);
resources.updateConfiguration(config, resources.getDisplayMetrics());
}
private static String locale2String(Locale locale) {
String localLanguage = locale.getLanguage(); // this may be empty
String localCountry = locale.getCountry(); // this may be empty
return localLanguage + "$" + localCountry;
}
private static Locale string2Locale(String str) {
Locale locale = string2LocaleReal(str);
if (locale == null) {
Log.e("LanguageUtils", "The string of " + str + " is not in the correct format.");
UtilsBridge.getSpUtils4Utils().remove(KEY_LOCALE);
}
return locale;
}
private static Locale string2LocaleReal(String str) {
if (!isRightFormatLocalStr(str)) {
return null;
}
try {
int splitIndex = str.indexOf("$");
return new Locale(str.substring(0, splitIndex), str.substring(splitIndex + 1));
} catch (Exception ignore) {
return null;
}
}
private static boolean isRightFormatLocalStr(String localStr) {
char[] chars = localStr.toCharArray();
int count = 0;
for (char c : chars) {
if (c == '$') {
if (count >= 1) {
return false;
}
++count;
}
}
return count == 1;
}
private static boolean isSameLocale(Locale l0, Locale l1) {
return UtilsBridge.equals(l1.getLanguage(), l0.getLanguage())
&& UtilsBridge.equals(l1.getCountry(), l0.getCountry());
}
private static Locale getLocal(Configuration configuration) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return configuration.getLocales().get(0);
} else {
return configuration.locale;
}
}
private static void setLocal(Configuration configuration, Locale locale) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLocale(locale);
} else {
configuration.locale = locale;
}
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/DialogUtils.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/DialogUtils.java | //package com.blankj.utilcode.util;
//
//import android.app.Activity;
//import android.app.Dialog;
//import android.content.Context;
//import android.content.ContextWrapper;
//import android.graphics.drawable.ColorDrawable;
//import android.os.Build;
//import android.support.annotation.LayoutRes;
//import android.support.annotation.NonNull;
//import android.util.Log;
//import android.view.LayoutInflater;
//import android.view.View;
//import android.view.Window;
//
//import java.util.HashMap;
//import java.util.TreeSet;
//
///**
// * <pre>
// * author: blankj
// * blog : http://blankj.com
// * time : 2019/08/26
// * desc : utils about dialog
// * </pre>
// */
//public class DialogUtils {
//
// private DialogUtils() {
// throw new UnsupportedOperationException("u can't instantiate me...");
// }
//
// public static void show(final Dialog dialog) {
// if (dialog == null) return;
// Utils.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Activity activity = getActivityByContext(dialog.getContext());
// if (!isActivityAlive(activity)) return;
// dialog.show();
// }
// });
// }
//
// public static void dismiss(final Dialog dialog) {
// if (dialog == null) return;
// Utils.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// dialog.dismiss();
// }
// });
// }
//
// public static void show(final Utils.TransActivityDelegate delegate) {
// Utils.TransActivity.start(null, delegate);
// }
//
// public static Dialog create(Activity activity, @LayoutRes int layoutId) {
// Dialog dialog = new Dialog(activity);
// View dialogContent = LayoutInflater.from(activity).inflate(layoutId, null);
//
// dialog.setContentView(dialogContent);
// Window window = dialog.getWindow();
// if (window != null) {
// window.setBackgroundDrawable(new ColorDrawable(0));
// }
//
// return dialog;
// }
//
// private static boolean isActivityAlive(final Activity activity) {
// return activity != null && !activity.isFinishing()
// && (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 || !activity.isDestroyed());
// }
//
// private static Activity getActivityByContext(Context context) {
// if (context instanceof Activity) return (Activity) context;
// while (context instanceof ContextWrapper) {
// if (context instanceof Activity) {
// return (Activity) context;
// }
// context = ((ContextWrapper) context).getBaseContext();
// }
// return null;
// }
//
// public static final class UtilsDialog extends Dialog {
//
// private int mPriority = 5;
//
// public UtilsDialog(@NonNull Context context) {
// this(context, 0);
// }
//
// public UtilsDialog(@NonNull Context context, int themeResId) {
// super(context, themeResId);
// }
//
// @Override
// public void show() {
// Utils.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Activity activity = getActivityByContext(getContext());
// if (!isActivityAlive(activity)) {
// Log.w("DialogUtils", "Activity is not alive.");
// return;
// }
// UtilsDialog.super.show();
// }
// });
// }
//
// @Override
// public void dismiss() {
// Utils.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// UtilsDialog.super.dismiss();
// }
// });
// }
//
// public void show(int priority) {
// mPriority = priority;
// show();
// }
// }
//}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/BrightnessUtils.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/BrightnessUtils.java | package com.blankj.utilcode.util;
import android.content.ContentResolver;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/02/08
* desc : utils about brightness
* </pre>
*/
public final class BrightnessUtils {
private BrightnessUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Return whether automatic brightness mode is enabled.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isAutoBrightnessEnabled() {
try {
int mode = Settings.System.getInt(
Utils.getApp().getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE
);
return mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**
* Enable or disable automatic brightness mode.
* <p>Must hold {@code <uses-permission android:name="android.permission.WRITE_SETTINGS" />}</p>
*
* @param enabled True to enabled, false otherwise.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean setAutoBrightnessEnabled(final boolean enabled) {
return Settings.System.putInt(
Utils.getApp().getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
enabled ? Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
: Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
);
}
/**
* 获取屏幕亮度
*
* @return 屏幕亮度 0-255
*/
public static int getBrightness() {
try {
return Settings.System.getInt(
Utils.getApp().getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS
);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return 0;
}
}
/**
* 设置屏幕亮度
* <p>需添加权限 {@code <uses-permission android:name="android.permission.WRITE_SETTINGS" />}</p>
* 并得到授权
*
* @param brightness 亮度值
*/
public static boolean setBrightness(@IntRange(from = 0, to = 255) final int brightness) {
ContentResolver resolver = Utils.getApp().getContentResolver();
boolean b = Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
resolver.notifyChange(Settings.System.getUriFor("screen_brightness"), null);
return b;
}
/**
* 设置窗口亮度
*
* @param window 窗口
* @param brightness 亮度值
*/
public static void setWindowBrightness(@NonNull final Window window,
@IntRange(from = 0, to = 255) final int brightness) {
WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = brightness / 255f;
window.setAttributes(lp);
}
/**
* 获取窗口亮度
*
* @param window 窗口
* @return 屏幕亮度 0-255
*/
public static int getWindowBrightness(@NonNull final Window window) {
WindowManager.LayoutParams lp = window.getAttributes();
float brightness = lp.screenBrightness;
if (brightness < 0) return getBrightness();
return (int) (brightness * 255);
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/ObjectUtils.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/ObjectUtils.java | package com.blankj.utilcode.util;
import android.os.Build;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.util.SparseLongArray;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.collection.LongSparseArray;
import androidx.collection.SimpleArrayMap;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/12/24
* desc : utils about object
* </pre>
*/
public final class ObjectUtils {
private ObjectUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Return whether object is empty.
*
* @param obj The object.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isEmpty(final Object obj) {
if (obj == null) {
return true;
}
if (obj.getClass().isArray() && Array.getLength(obj) == 0) {
return true;
}
if (obj instanceof CharSequence && obj.toString().length() == 0) {
return true;
}
if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
return true;
}
if (obj instanceof Map && ((Map) obj).isEmpty()) {
return true;
}
if (obj instanceof SimpleArrayMap && ((SimpleArrayMap) obj).isEmpty()) {
return true;
}
if (obj instanceof SparseArray && ((SparseArray) obj).size() == 0) {
return true;
}
if (obj instanceof SparseBooleanArray && ((SparseBooleanArray) obj).size() == 0) {
return true;
}
if (obj instanceof SparseIntArray && ((SparseIntArray) obj).size() == 0) {
return true;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
if (obj instanceof SparseLongArray && ((SparseLongArray) obj).size() == 0) {
return true;
}
}
if (obj instanceof LongSparseArray && ((LongSparseArray) obj).size() == 0) {
return true;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if (obj instanceof android.util.LongSparseArray
&& ((android.util.LongSparseArray) obj).size() == 0) {
return true;
}
}
return false;
}
public static boolean isEmpty(final CharSequence obj) {
return obj == null || obj.toString().length() == 0;
}
public static boolean isEmpty(final Collection obj) {
return obj == null || obj.isEmpty();
}
public static boolean isEmpty(final Map obj) {
return obj == null || obj.isEmpty();
}
public static boolean isEmpty(final SimpleArrayMap obj) {
return obj == null || obj.isEmpty();
}
public static boolean isEmpty(final SparseArray obj) {
return obj == null || obj.size() == 0;
}
public static boolean isEmpty(final SparseBooleanArray obj) {
return obj == null || obj.size() == 0;
}
public static boolean isEmpty(final SparseIntArray obj) {
return obj == null || obj.size() == 0;
}
public static boolean isEmpty(final LongSparseArray obj) {
return obj == null || obj.size() == 0;
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public static boolean isEmpty(final SparseLongArray obj) {
return obj == null || obj.size() == 0;
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public static boolean isEmpty(final android.util.LongSparseArray obj) {
return obj == null || obj.size() == 0;
}
/**
* Return whether object is not empty.
*
* @param obj The object.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isNotEmpty(final Object obj) {
return !isEmpty(obj);
}
public static boolean isNotEmpty(final CharSequence obj) {
return !isEmpty(obj);
}
public static boolean isNotEmpty(final Collection obj) {
return !isEmpty(obj);
}
public static boolean isNotEmpty(final Map obj) {
return !isEmpty(obj);
}
public static boolean isNotEmpty(final SimpleArrayMap obj) {
return !isEmpty(obj);
}
public static boolean isNotEmpty(final SparseArray obj) {
return !isEmpty(obj);
}
public static boolean isNotEmpty(final SparseBooleanArray obj) {
return !isEmpty(obj);
}
public static boolean isNotEmpty(final SparseIntArray obj) {
return !isEmpty(obj);
}
public static boolean isNotEmpty(final LongSparseArray obj) {
return !isEmpty(obj);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public static boolean isNotEmpty(final SparseLongArray obj) {
return !isEmpty(obj);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public static boolean isNotEmpty(final android.util.LongSparseArray obj) {
return !isEmpty(obj);
}
/**
* Return whether object1 is equals to object2.
*
* @param o1 The first object.
* @param o2 The second object.
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean equals(final Object o1, final Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
/**
* Returns 0 if the arguments are identical and {@code
* c.compare(a, b)} otherwise.
* Consequently, if both arguments are {@code null} 0
* is returned.
*/
public static <T> int compare(T a, T b, @NonNull Comparator<? super T> c) {
return (a == b) ? 0 : c.compare(a, b);
}
/**
* Checks that the specified object reference is not {@code null}.
*/
public static <T> T requireNonNull(T obj) {
if (obj == null) throw new NullPointerException();
return obj;
}
/**
* Checks that the specified object reference is not {@code null} and
* throws a customized {@link NullPointerException} if it is.
*/
public static <T> T requireNonNull(T obj, String ifNullTip) {
if (obj == null) throw new NullPointerException(ifNullTip);
return obj;
}
/**
* Require the objects are not null.
*
* @param objects The object.
* @throws NullPointerException if any object is null in objects
*/
public static void requireNonNulls(final Object... objects) {
if (objects == null) throw new NullPointerException();
for (Object object : objects) {
if (object == null) throw new NullPointerException();
}
}
/**
* Return the nonnull object or default object.
*
* @param object The object.
* @param defaultObject The default object to use with the object is null.
* @param <T> The value type.
* @return the nonnull object or default object
*/
public static <T> T getOrDefault(final T object, final T defaultObject) {
if (object == null) {
return defaultObject;
}
return object;
}
/**
* Returns the result of calling {@code toString} for a non-{@code
* null} argument and {@code "null"} for a {@code null} argument.
*/
public static String toString(Object obj) {
return String.valueOf(obj);
}
/**
* Returns the result of calling {@code toString} on the first
* argument if the first argument is not {@code null} and returns
* the second argument otherwise.
*/
public static String toString(Object o, String nullDefault) {
return (o != null) ? o.toString() : nullDefault;
}
/**
* Return the hash code of object.
*
* @param o The object.
* @return the hash code of object
*/
public static int hashCode(final Object o) {
return o != null ? o.hashCode() : 0;
}
/**
* Return the hash code of objects.
*/
public static int hashCodes(Object... values) {
return Arrays.hashCode(values);
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/UiMessageUtils.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/UiMessageUtils.java | package com.blankj.utilcode.util;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/10/20
* desc : utils about ui message can replace LocalBroadcastManager
* </pre>
*/
public final class UiMessageUtils implements Handler.Callback {
private static final String TAG = "UiMessageUtils";
private static final boolean DEBUG = UtilsBridge.isAppDebug();
private final Handler mHandler = new Handler(Looper.getMainLooper(), this);
private final UiMessage mMessage = new UiMessage(null);
private final SparseArray<List<UiMessageCallback>> mListenersSpecific = new SparseArray<>();
private final List<UiMessageCallback> mListenersUniversal = new ArrayList<>();
private final List<UiMessageCallback> mDefensiveCopyList = new ArrayList<>();
public static UiMessageUtils getInstance() {
return LazyHolder.INSTANCE;
}
private UiMessageUtils() {
}
/**
* Sends an empty Message containing only the message ID.
*
* @param id The message ID.
*/
public final void send(final int id) {
mHandler.sendEmptyMessage(id);
}
/**
* Sends a message containing the ID and an arbitrary object.
*
* @param id The message ID.
* @param obj The object.
*/
public final void send(final int id, @NonNull final Object obj) {
mHandler.sendMessage(mHandler.obtainMessage(id, obj));
}
/**
* Add listener for specific type of message by its ID.
* Don't forget to call {@link #removeListener(UiMessageCallback)} or
* {@link #removeListeners(int)}
*
* @param id The ID of message that will be only notified to listener.
* @param listener The listener.
*/
public void addListener(int id, @NonNull final UiMessageCallback listener) {
synchronized (mListenersSpecific) {
List<UiMessageCallback> idListeners = mListenersSpecific.get(id);
if (idListeners == null) {
idListeners = new ArrayList<>();
mListenersSpecific.put(id, idListeners);
}
if (!idListeners.contains(listener)) {
idListeners.add(listener);
}
}
}
/**
* Add listener for all messages.
*
* @param listener The listener.
*/
public void addListener(@NonNull final UiMessageCallback listener) {
synchronized (mListenersUniversal) {
if (!mListenersUniversal.contains(listener)) {
mListenersUniversal.add(listener);
} else {
if (DEBUG) {
Log.w(TAG, "Listener is already added. " + listener.toString());
}
}
}
}
/**
* Remove listener for all messages.
*
* @param listener The listener to remove.
*/
public void removeListener(@NonNull final UiMessageCallback listener) {
synchronized (mListenersUniversal) {
if (DEBUG && !mListenersUniversal.contains(listener)) {
Log.w(TAG, "Trying to remove a listener that is not registered. " + listener.toString());
}
mListenersUniversal.remove(listener);
}
}
/**
* Remove all listeners for desired message ID.
*
* @param id The id of the message to stop listening to.
*/
public void removeListeners(final int id) {
if (DEBUG) {
final List<UiMessageCallback> callbacks = mListenersSpecific.get(id);
if (callbacks == null || callbacks.size() == 0) {
Log.w(TAG, "Trying to remove specific listeners that are not registered. ID " + id);
}
}
synchronized (mListenersSpecific) {
mListenersSpecific.delete(id);
}
}
/**
* Remove the specific listener for desired message ID.
*
* @param id The id of the message to stop listening to.
* @param listener The listener which should be removed.
*/
public void removeListener(final int id, @NonNull final UiMessageCallback listener) {
synchronized (mListenersSpecific) {
final List<UiMessageCallback> callbacks = this.mListenersSpecific.get(id);
if (callbacks != null && !callbacks.isEmpty()) {
if (DEBUG) {
if (!callbacks.contains(listener)) {
Log.w(TAG, "Trying to remove specific listener that is not registered. ID " + id + ", " + listener);
return;
}
}
callbacks.remove(listener);
} else {
if (DEBUG) {
Log.w(TAG, "Trying to remove specific listener that is not registered. ID " + id + ", " + listener);
}
}
}
}
@Override
public boolean handleMessage(Message msg) {
mMessage.setMessage(msg);
if (DEBUG) {
logMessageHandling(mMessage);
}
// process listeners for specified type of message what
synchronized (mListenersSpecific) {
final List<UiMessageCallback> idListeners = mListenersSpecific.get(msg.what);
if (idListeners != null) {
if (idListeners.size() == 0) {
mListenersSpecific.remove(msg.what);
} else {
mDefensiveCopyList.addAll(idListeners);
for (final UiMessageCallback callback : mDefensiveCopyList) {
callback.handleMessage(mMessage);
}
mDefensiveCopyList.clear();
}
}
}
// process universal listeners
synchronized (mListenersUniversal) {
if (mListenersUniversal.size() > 0) {
mDefensiveCopyList.addAll(mListenersUniversal);
for (final UiMessageCallback callback : mDefensiveCopyList) {
callback.handleMessage(mMessage);
}
mDefensiveCopyList.clear();
}
}
mMessage.setMessage(null);
return true;
}
private void logMessageHandling(@NonNull final UiMessage msg) {
final List<UiMessageCallback> idListeners = mListenersSpecific.get(msg.getId());
if ((idListeners == null || idListeners.size() == 0) && mListenersUniversal.size() == 0) {
Log.w(TAG, "Delivering FAILED for message ID " + msg.getId() + ". No listeners. " + msg.toString());
} else {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Delivering message ID ");
stringBuilder.append(msg.getId());
stringBuilder.append(", Specific listeners: ");
if (idListeners == null || idListeners.size() == 0) {
stringBuilder.append(0);
} else {
stringBuilder.append(idListeners.size());
stringBuilder.append(" [");
for (int i = 0; i < idListeners.size(); i++) {
stringBuilder.append(idListeners.get(i).getClass().getSimpleName());
if (i < idListeners.size() - 1) {
stringBuilder.append(",");
}
}
stringBuilder.append("]");
}
stringBuilder.append(", Universal listeners: ");
synchronized (mListenersUniversal) {
if (mListenersUniversal.size() == 0) {
stringBuilder.append(0);
} else {
stringBuilder.append(mListenersUniversal.size());
stringBuilder.append(" [");
for (int i = 0; i < mListenersUniversal.size(); i++) {
stringBuilder.append(mListenersUniversal.get(i).getClass().getSimpleName());
if (i < mListenersUniversal.size() - 1) {
stringBuilder.append(",");
}
}
stringBuilder.append("], Message: ");
}
}
stringBuilder.append(msg.toString());
Log.v(TAG, stringBuilder.toString());
}
}
public static final class UiMessage {
private Message mMessage;
private UiMessage(final Message message) {
this.mMessage = message;
}
private void setMessage(final Message message) {
mMessage = message;
}
public int getId() {
return mMessage.what;
}
public Object getObject() {
return mMessage.obj;
}
@Override
public String toString() {
return "{ " +
"id=" + getId() +
", obj=" + getObject() +
" }";
}
}
public interface UiMessageCallback {
void handleMessage(@NonNull UiMessage localMessage);
}
private static final class LazyHolder {
private static final UiMessageUtils INSTANCE = new UiMessageUtils();
}
}
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | false |
Blankj/AndroidUtilCode | https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utilcode/src/main/java/com/blankj/utilcode/util/CollectionUtils.java | lib/utilcode/src/main/java/com/blankj/utilcode/util/CollectionUtils.java | package com.blankj.utilcode.util;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/07/26
* desc : utils about collection
* </pre>
*/
public final class CollectionUtils {
private CollectionUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
///////////////////////////////////////////////////////////////////////////
// listOf
///////////////////////////////////////////////////////////////////////////
/**
* Returns a new read-only list of given elements.
*
* @param array The array.
* @return a new read-only list of given elements
*/
@SafeVarargs
public static <E> List<E> newUnmodifiableList(E... array) {
return Collections.unmodifiableList(newArrayList(array));
}
/**
* Returns a new read-only list only of those given elements, that are not null.
*
* @param array The array.
* @return a new read-only list only of those given elements, that are not null
*/
@SafeVarargs
public static <E> List<E> newUnmodifiableListNotNull(E... array) {
return Collections.unmodifiableList(newArrayListNotNull(array));
}
@SafeVarargs
public static <E> ArrayList<E> newArrayList(E... array) {
ArrayList<E> list = new ArrayList<>();
if (array == null || array.length == 0) return list;
for (E e : array) {
list.add(e);
}
return list;
}
@SafeVarargs
public static <E> ArrayList<E> newArrayListNotNull(E... array) {
ArrayList<E> list = new ArrayList<>();
if (array == null || array.length == 0) return list;
for (E e : array) {
if (e == null) continue;
list.add(e);
}
return list;
}
@SafeVarargs
public static <E> LinkedList<E> newLinkedList(E... array) {
LinkedList<E> list = new LinkedList<>();
if (array == null || array.length == 0) return list;
for (E e : array) {
list.add(e);
}
return list;
}
@SafeVarargs
public static <E> LinkedList<E> newLinkedListNotNull(E... array) {
LinkedList<E> list = new LinkedList<>();
if (array == null || array.length == 0) return list;
for (E e : array) {
if (e == null) continue;
list.add(e);
}
return list;
}
@SafeVarargs
public static <E> HashSet<E> newHashSet(E... array) {
HashSet<E> set = new HashSet<>();
if (array == null || array.length == 0) return set;
for (E e : array) {
set.add(e);
}
return set;
}
@SafeVarargs
public static <E> HashSet<E> newHashSetNotNull(E... array) {
HashSet<E> set = new HashSet<>();
if (array == null || array.length == 0) return set;
for (E e : array) {
if (e == null) continue;
set.add(e);
}
return set;
}
@SafeVarargs
public static <E> TreeSet<E> newTreeSet(Comparator<E> comparator, E... array) {
TreeSet<E> set = new TreeSet<>(comparator);
if (array == null || array.length == 0) return set;
for (E e : array) {
set.add(e);
}
return set;
}
@SafeVarargs
public static <E> TreeSet<E> newTreeSetNotNull(Comparator<E> comparator, E... array) {
TreeSet<E> set = new TreeSet<>(comparator);
if (array == null || array.length == 0) return set;
for (E e : array) {
if (e == null) continue;
set.add(e);
}
return set;
}
public static Collection newSynchronizedCollection(Collection collection) {
return Collections.synchronizedCollection(collection);
}
public static Collection newUnmodifiableCollection(Collection collection) {
return Collections.unmodifiableCollection(collection);
}
/**
* Returns a {@link Collection} containing the union
* of the given {@link Collection}s.
* <p>
* The cardinality of each element in the returned {@link Collection}
* will be equal to the maximum of the cardinality of that element
* in the two given {@link Collection}s.
*
* @param a the first collection
* @param b the second collection
* @return the union of the two collections
* @see Collection#addAll
*/
public static Collection union(final Collection a, final Collection b) {
if (a == null && b == null) return new ArrayList();
if (a == null) return new ArrayList<Object>(b);
if (b == null) return new ArrayList<Object>(a);
ArrayList<Object> list = new ArrayList<>();
Map<Object, Integer> mapA = getCardinalityMap(a);
Map<Object, Integer> mapB = getCardinalityMap(b);
Set<Object> elts = new HashSet<Object>(a);
elts.addAll(b);
for (Object obj : elts) {
for (int i = 0, m = Math.max(getFreq(obj, mapA), getFreq(obj, mapB)); i < m; i++) {
list.add(obj);
}
}
return list;
}
/**
* Returns a {@link Collection} containing the intersection
* of the given {@link Collection}s.
* <p>
* The cardinality of each element in the returned {@link Collection}
* will be equal to the minimum of the cardinality of that element
* in the two given {@link Collection}s.
*
* @param a the first collection
* @param b the second collection
* @return the intersection of the two collections
* @see Collection#retainAll
*/
public static Collection intersection(final Collection a, final Collection b) {
if (a == null || b == null) return new ArrayList();
ArrayList<Object> list = new ArrayList<>();
Map mapA = getCardinalityMap(a);
Map mapB = getCardinalityMap(b);
Set<Object> elts = new HashSet<Object>(a);
elts.addAll(b);
for (Object obj : elts) {
for (int i = 0, m = Math.min(getFreq(obj, mapA), getFreq(obj, mapB)); i < m; i++) {
list.add(obj);
}
}
return list;
}
private static int getFreq(final Object obj, final Map freqMap) {
Integer count = (Integer) freqMap.get(obj);
if (count != null) {
return count;
}
return 0;
}
/**
* Returns a {@link Collection} containing the exclusive disjunction
* (symmetric difference) of the given {@link Collection}s.
* <p>
* The cardinality of each element <i>e</i> in the returned {@link Collection}
* will be equal to
* <tt>max(cardinality(<i>e</i>,<i>a</i>),cardinality(<i>e</i>,<i>b</i>)) - min(cardinality(<i>e</i>,<i>a</i>),cardinality(<i>e</i>,<i>b</i>))</tt>.
* <p>
* This is equivalent to
* <tt>{@link #subtract subtract}({@link #union union(a,b)},{@link #intersection intersection(a,b)})</tt>
* or
* <tt>{@link #union union}({@link #subtract subtract(a,b)},{@link #subtract subtract(b,a)})</tt>.
*
* @param a the first collection
* @param b the second collection
* @return the symmetric difference of the two collections
*/
public static Collection disjunction(final Collection a, final Collection b) {
if (a == null && b == null) return new ArrayList();
if (a == null) return new ArrayList<Object>(b);
if (b == null) return new ArrayList<Object>(a);
ArrayList<Object> list = new ArrayList<>();
Map mapA = getCardinalityMap(a);
Map mapB = getCardinalityMap(b);
Set<Object> elts = new HashSet<Object>(a);
elts.addAll(b);
for (Object obj : elts) {
for (int i = 0, m = ((Math.max(getFreq(obj, mapA), getFreq(obj, mapB)))
- (Math.min(getFreq(obj, mapA), getFreq(obj, mapB)))); i < m; i++) {
list.add(obj);
}
}
return list;
}
/**
* Returns a new {@link Collection} containing <tt><i>a</i> - <i>b</i></tt>.
* The cardinality of each element <i>e</i> in the returned {@link Collection}
* will be the cardinality of <i>e</i> in <i>a</i> minus the cardinality
* of <i>e</i> in <i>b</i>, or zero, whichever is greater.
*
* @param a the collection to subtract from
* @param b the collection to subtract
* @return a new collection with the results
* @see Collection#removeAll
*/
public static Collection subtract(final Collection a, final Collection b) {
if (a == null) return new ArrayList();
if (b == null) return new ArrayList<Object>(a);
ArrayList<Object> list = new ArrayList<Object>(a);
for (Object o : b) {
list.remove(o);
}
return list;
}
/**
* Returns <code>true</code> iff at least one element is in both collections.
* <p>
* In other words, this method returns <code>true</code> iff the
* {@link #intersection} of <i>coll1</i> and <i>coll2</i> is not empty.
*
* @param coll1 the first collection
* @param coll2 the first collection
* @return <code>true</code> iff the intersection of the collections is non-empty
* @see #intersection
*/
public static boolean containsAny(final Collection coll1, final Collection coll2) {
if (coll1 == null || coll2 == null) return false;
if (coll1.size() < coll2.size()) {
for (Object o : coll1) {
if (coll2.contains(o)) {
return true;
}
}
} else {
for (Object o : coll2) {
if (coll1.contains(o)) {
return true;
}
}
}
return false;
}
/**
* Returns a {@link Map} mapping each unique element in the given
* {@link Collection} to an {@link Integer} representing the number
* of occurrences of that element in the {@link Collection}.
* <p>
* Only those elements present in the collection will appear as
* keys in the map.
*
* @param coll the collection to get the cardinality map for, must not be null
* @return the populated cardinality map
*/
public static Map<Object, Integer> getCardinalityMap(final Collection coll) {
Map<Object, Integer> count = new HashMap<>();
if (coll == null) return count;
for (Object obj : coll) {
Integer c = count.get(obj);
if (c == null) {
count.put(obj, 1);
} else {
count.put(obj, c + 1);
}
}
return count;
}
/**
* Returns <tt>true</tt> iff <i>a</i> is a sub-collection of <i>b</i>,
* that is, iff the cardinality of <i>e</i> in <i>a</i> is less
* than or equal to the cardinality of <i>e</i> in <i>b</i>,
* for each element <i>e</i> in <i>a</i>.
*
* @param a the first (sub?) collection
* @param b the second (super?) collection
* @return <code>true</code> iff <i>a</i> is a sub-collection of <i>b</i>
* @see #isProperSubCollection
* @see Collection#containsAll
*/
public static boolean isSubCollection(final Collection a, final Collection b) {
if (a == null || b == null) return false;
Map mapA = getCardinalityMap(a);
Map mapB = getCardinalityMap(b);
for (Object obj : a) {
if (getFreq(obj, mapA) > getFreq(obj, mapB)) {
return false;
}
}
return true;
}
/**
* Returns <tt>true</tt> iff <i>a</i> is a <i>proper</i> sub-collection of <i>b</i>,
* that is, iff the cardinality of <i>e</i> in <i>a</i> is less
* than or equal to the cardinality of <i>e</i> in <i>b</i>,
* for each element <i>e</i> in <i>a</i>, and there is at least one
* element <i>f</i> such that the cardinality of <i>f</i> in <i>b</i>
* is strictly greater than the cardinality of <i>f</i> in <i>a</i>.
* <p>
* The implementation assumes
* <ul>
* <li><code>a.size()</code> and <code>b.size()</code> represent the
* total cardinality of <i>a</i> and <i>b</i>, resp. </li>
* <li><code>a.size() < Integer.MAXVALUE</code></li>
* </ul>
*
* @param a the first (sub?) collection
* @param b the second (super?) collection
* @return <code>true</code> iff <i>a</i> is a <i>proper</i> sub-collection of <i>b</i>
* @see #isSubCollection
* @see Collection#containsAll
*/
public static boolean isProperSubCollection(final Collection a, final Collection b) {
if (a == null || b == null) return false;
return a.size() < b.size() && isSubCollection(a, b);
}
/**
* Returns <tt>true</tt> iff the given {@link Collection}s contain
* exactly the same elements with exactly the same cardinalities.
* <p>
* That is, iff the cardinality of <i>e</i> in <i>a</i> is
* equal to the cardinality of <i>e</i> in <i>b</i>,
* for each element <i>e</i> in <i>a</i> or <i>b</i>.
*
* @param a the first collection
* @param b the second collection
* @return <code>true</code> iff the collections contain the same elements with the same cardinalities.
*/
public static boolean isEqualCollection(final Collection a, final Collection b) {
if (a == null || b == null) return false;
if (a.size() != b.size()) {
return false;
} else {
Map mapA = getCardinalityMap(a);
Map mapB = getCardinalityMap(b);
if (mapA.size() != mapB.size()) {
return false;
} else {
for (Object obj : mapA.keySet()) {
if (getFreq(obj, mapA) != getFreq(obj, mapB)) {
return false;
}
}
return true;
}
}
}
/**
* Returns the number of occurrences of <i>obj</i> in <i>coll</i>.
*
* @param obj the object to find the cardinality of
* @param coll the collection to search
* @return the the number of occurrences of obj in coll
*/
public static <E> int cardinality(E obj, final Collection<E> coll) {
if (coll == null) return 0;
if (coll instanceof Set) {
return (coll.contains(obj) ? 1 : 0);
}
int count = 0;
if (obj == null) {
for (E e : coll) {
if (e == null) {
count++;
}
}
} else {
for (E e : coll) {
if (obj.equals(e)) {
count++;
}
}
}
return count;
}
/**
* Finds the first element in the given collection which matches the given predicate.
* <p>
* If the input collection or predicate is null, or no element of the collection
* matches the predicate, null is returned.
*
* @param collection the collection to search, may be null
* @param predicate the predicate to use, may be null
* @return the first element of the collection which matches the predicate or null if none could be found
*/
public static <E> E find(Collection<E> collection, Predicate<E> predicate) {
if (collection == null || predicate == null) return null;
for (E item : collection) {
if (predicate.evaluate(item)) {
return item;
}
}
return null;
}
/**
* Executes the given closure on each element in the collection.
* <p>
* If the input collection or closure is null, there is no change made.
*
* @param collection the collection to get the input from, may be null
* @param closure the closure to perform, may be null
*/
public static <E> void forAllDo(Collection<E> collection, Closure<E> closure) {
if (collection == null || closure == null) return;
int index = 0;
for (E e : collection) {
closure.execute(index++, e);
}
}
/**
* Filter the collection by applying a Predicate to each element. If the
* predicate returns false, remove the element.
* <p>
* If the input collection or predicate is null, there is no change made.
*
* @param collection the collection to get the input from, may be null
* @param predicate the predicate to use as a filter, may be null
*/
public static <E> void filter(Collection<E> collection, Predicate<E> predicate) {
if (collection == null || predicate == null) return;
for (Iterator it = collection.iterator(); it.hasNext(); ) {
if (!predicate.evaluate((E) it.next())) {
it.remove();
}
}
}
/**
* Selects all elements from input collection which match the given predicate
* into an output collection.
* <p>
* A <code>null</code> predicate matches no elements.
*
* @param inputCollection the collection to get the input from, may not be null
* @param predicate the predicate to use, may be null
* @return the elements matching the predicate (new list)
* @throws NullPointerException if the input collection is null
*/
public static <E> Collection<E> select(Collection<E> inputCollection, Predicate<E> predicate) {
if (inputCollection == null || predicate == null) return new ArrayList<>();
ArrayList<E> answer = new ArrayList<>(inputCollection.size());
for (E o : inputCollection) {
if (predicate.evaluate(o)) {
answer.add(o);
}
}
return answer;
}
/**
* Selects all elements from inputCollection which don't match the given predicate
* into an output collection.
* <p>
* If the input predicate is <code>null</code>, the result is an empty list.
*
* @param inputCollection the collection to get the input from, may not be null
* @param predicate the predicate to use, may be null
* @return the elements <b>not</b> matching the predicate (new list)
* @throws NullPointerException if the input collection is null
*/
public static <E> Collection<E> selectRejected(Collection<E> inputCollection, Predicate<E> predicate) {
if (inputCollection == null || predicate == null) return new ArrayList<>();
ArrayList<E> answer = new ArrayList<>(inputCollection.size());
for (E o : inputCollection) {
if (!predicate.evaluate(o)) {
answer.add(o);
}
}
return answer;
}
/**
* Transform the collection by applying a Transformer to each element.
* <p>
* If the input collection or transformer is null, there is no change made.
* <p>
* This routine is best for Lists, for which set() is used to do the
* transformations "in place." For other Collections, clear() and addAll()
* are used to replace elements.
* <p>
* If the input collection controls its input, such as a Set, and the
* Transformer creates duplicates (or are otherwise invalid), the
* collection may reduce in size due to calling this method.
*
* @param collection the collection to get the input from, may be null
* @param transformer the transformer to perform, may be null
*/
public static <E1, E2> void transform(Collection<E1> collection, Transformer<E1, E2> transformer) {
if (collection == null || transformer == null) return;
if (collection instanceof List) {
List list = (List) collection;
for (ListIterator it = list.listIterator(); it.hasNext(); ) {
it.set(transformer.transform((E1) it.next()));
}
} else {
Collection resultCollection = collect(collection, transformer);
collection.clear();
collection.addAll(resultCollection);
}
}
/**
* Returns a new Collection consisting of the elements of inputCollection transformed
* by the given transformer.
* <p>
* If the input transformer is null, the result is an empty list.
*
* @param inputCollection the collection to get the input from, may be null
* @param transformer the transformer to use, may be null
* @return the transformed result (new list)
*/
public static <E1, E2> Collection<E2> collect(final Collection<E1> inputCollection,
final Transformer<E1, E2> transformer) {
List<E2> answer = new ArrayList<>();
if (inputCollection == null || transformer == null) return answer;
for (E1 e1 : inputCollection) {
answer.add(transformer.transform(e1));
}
return answer;
}
/**
* Counts the number of elements in the input collection that match the predicate.
* <p>
* A <code>null</code> collection or predicate matches no elements.
*
* @param collection the collection to get the input from, may be null
* @param predicate the predicate to use, may be null
* @return the number of matches for the predicate in the collection
*/
public static <E> int countMatches(Collection<E> collection, Predicate<E> predicate) {
if (collection == null || predicate == null) return 0;
int count = 0;
for (E o : collection) {
if (predicate.evaluate(o)) {
count++;
}
}
return count;
}
/**
* Answers true if a predicate is true for at least one element of a collection.
* <p>
* A <code>null</code> collection or predicate returns false.
*
* @param collection the collection to get the input from, may be null
* @param predicate the predicate to use, may be null
* @return true if at least one element of the collection matches the predicate
*/
public static <E> boolean exists(Collection<E> collection, Predicate<E> predicate) {
if (collection == null || predicate == null) return false;
for (E o : collection) {
if (predicate.evaluate(o)) {
return true;
}
}
return false;
}
/**
* Adds an element to the collection unless the element is null.
*
* @param collection the collection to add to, may be null
* @param object the object to add, if null it will not be added
* @return true if the collection changed
*/
public static <E> boolean addIgnoreNull(Collection<E> collection, E object) {
if (collection == null) return false;
return (object != null && collection.add(object));
}
/**
* Adds all elements in the iteration to the given collection.
*
* @param collection the collection to add to, may be null
* @param iterator the iterator of elements to add, may be null
*/
public static <E> void addAll(Collection<E> collection, Iterator<E> iterator) {
if (collection == null || iterator == null) return;
while (iterator.hasNext()) {
collection.add(iterator.next());
}
}
/**
* Adds all elements in the enumeration to the given collection.
*
* @param collection the collection to add to, may be null
* @param enumeration the enumeration of elements to add, may be null
*/
public static <E> void addAll(Collection<E> collection, Enumeration<E> enumeration) {
if (collection == null || enumeration == null) return;
while (enumeration.hasMoreElements()) {
collection.add(enumeration.nextElement());
}
}
/**
* Adds all elements in the array to the given collection.
*
* @param collection the collection to add to, may be null
* @param elements the array of elements to add, may be null
*/
public static <E> void addAll(Collection<E> collection, E[] elements) {
if (collection == null || elements == null || elements.length == 0) return;
collection.addAll(Arrays.asList(elements));
}
/**
* Returns the <code>index</code>-th value in <code>object</code>, throwing
* <code>IndexOutOfBoundsException</code> if there is no such element or
* <code>IllegalArgumentException</code> if <code>object</code> is not an
* instance of one of the supported types.
* <p>
* The supported types, and associated semantics are:
* <ul>
* <li> Map -- the value returned is the <code>Map.Entry</code> in position
* <code>index</code> in the map's <code>entrySet</code> iterator,
* if there is such an entry.</li>
* <li> List -- this method is equivalent to the list's get method.</li>
* <li> Array -- the <code>index</code>-th array entry is returned,
* if there is such an entry; otherwise an <code>IndexOutOfBoundsException</code>
* is thrown.</li>
* <li> Collection -- the value returned is the <code>index</code>-th object
* returned by the collection's default iterator, if there is such an element.</li>
* <li> Iterator or Enumeration -- the value returned is the
* <code>index</code>-th object in the Iterator/Enumeration, if there
* is such an element. The Iterator/Enumeration is advanced to
* <code>index</code> (or to the end, if <code>index</code> exceeds the
* number of entries) as a side effect of this method.</li>
* </ul>
*
* @param object the object to get a value from
* @param index the index to get
* @return the object at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
* @throws IllegalArgumentException if the object type is invalid
*/
public static Object get(Object object, int index) {
if (object == null) return null;
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative: " + index);
}
if (object instanceof Map) {
Map map = (Map) object;
Iterator iterator = map.entrySet().iterator();
return get(iterator, index);
} else if (object instanceof List) {
return ((List) object).get(index);
} else if (object instanceof Object[]) {
return ((Object[]) object)[index];
} else if (object instanceof Iterator) {
Iterator it = (Iterator) object;
while (it.hasNext()) {
index--;
if (index == -1) {
return it.next();
} else {
it.next();
}
}
throw new IndexOutOfBoundsException("Entry does not exist: " + index);
} else if (object instanceof Collection) {
Iterator iterator = ((Collection) object).iterator();
return get(iterator, index);
} else if (object instanceof Enumeration) {
Enumeration it = (Enumeration) object;
while (it.hasMoreElements()) {
index--;
if (index == -1) {
return it.nextElement();
} else {
it.nextElement();
}
}
throw new IndexOutOfBoundsException("Entry does not exist: " + index);
} else {
try {
return Array.get(object, index);
} catch (IllegalArgumentException ex) {
throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
}
}
}
/**
* Gets the size of the collection/iterator specified.
* <p>
* This method can handles objects as follows
* <ul>
* <li>Collection - the collection size
* <li>Map - the map size
* <li>Array - the array size
* <li>Iterator - the number of elements remaining in the iterator
* <li>Enumeration - the number of elements remaining in the enumeration
* </ul>
*
* @param object the object to get the size of
* @return the size of the specified collection
* @throws IllegalArgumentException thrown if object is not recognised or null
*/
public static int size(Object object) {
if (object == null) return 0;
int total = 0;
if (object instanceof Map) {
total = ((Map) object).size();
} else if (object instanceof Collection) {
total = ((Collection) object).size();
} else if (object instanceof Object[]) {
total = ((Object[]) object).length;
} else if (object instanceof Iterator) {
Iterator it = (Iterator) object;
while (it.hasNext()) {
total++;
it.next();
}
} else if (object instanceof Enumeration) {
Enumeration it = (Enumeration) object;
while (it.hasMoreElements()) {
total++;
it.nextElement();
}
} else {
try {
total = Array.getLength(object);
} catch (IllegalArgumentException ex) {
throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
}
}
return total;
}
/**
* Checks if the specified collection/array/iterator is empty.
* <p>
* This method can handles objects as follows
* <ul>
* <li>Collection - via collection isEmpty
* <li>Map - via map isEmpty
* <li>Array - using array size
* <li>Iterator - via hasNext
* <li>Enumeration - via hasMoreElements
* </ul>
* <p>
* Note: This method is named to avoid clashing with
* {@link #isEmpty(Collection)}.
*
* @param object the object to get the size of, not null
* @return true if empty
* @throws IllegalArgumentException thrown if object is not recognised or null
*/
public static boolean sizeIsEmpty(Object object) {
if (object == null) return true;
if (object instanceof Collection) {
return ((Collection) object).isEmpty();
} else if (object instanceof Map) {
return ((Map) object).isEmpty();
} else if (object instanceof Object[]) {
return ((Object[]) object).length == 0;
} else if (object instanceof Iterator) {
return !((Iterator) object).hasNext();
} else if (object instanceof Enumeration) {
return !((Enumeration) object).hasMoreElements();
} else {
try {
return Array.getLength(object) == 0;
} catch (IllegalArgumentException ex) {
throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName());
}
}
}
/**
* Null-safe check if the specified collection is empty.
* <p>
* Null returns true.
*
* @param coll the collection to check, may be null
* @return true if empty or null
*/
public static boolean isEmpty(Collection coll) {
return coll == null || coll.size() == 0;
}
/**
* Null-safe check if the specified collection is not empty.
* <p>
* Null returns false.
*
* @param coll the collection to check, may be null
* @return true if non-null and non-empty
*/
public static boolean isNotEmpty(Collection coll) {
return !isEmpty(coll);
}
/**
* Returns a collection containing all the elements in <code>collection</code>
* that are also in <code>retain</code>. The cardinality of an element <code>e</code>
* in the returned collection is the same as the cardinality of <code>e</code>
* in <code>collection</code> unless <code>retain</code> does not contain <code>e</code>, in which
* case the cardinality is zero. This method is useful if you do not wish to modify
* the collection <code>c</code> and thus cannot call <code>c.retainAll(retain);</code>.
*
* @param collection the collection whose contents are the target of the #retailAll operation
| java | Apache-2.0 | 7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809 | 2026-01-04T14:46:34.292032Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.